Guid & GetHashCode uniqueness

后端 未结 5 1315
情话喂你
情话喂你 2020-12-06 04:37

Given the following key:

int key = Guid.NewGuid().GetHashCode();

Is this key unique as the uniqueness of Guid?

5条回答
  •  没有蜡笔的小新
    2020-12-06 04:45

    Just today I've noticed another problem of the Guid.GetHashCode(): in Microsoft .NET implementation, not every "byte" of the Guid is hashed: there are 6 bytes of the Guid that aren't hashed, so any change to one of them won't ever change the hash code.

    We can see it in the reference source:

    return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k);
    

    so the _d, _e, _g, _h, _i, _j bytes aren't hashed. This has an important impact with "sequential" Guids, like:

    c482fbe1-9f16-4ae9-a05c-383478ec9d13
    c482fbe1-9f16-4ae9-a05c-383478ec9d14
    c482fbe1-9f16-4ae9-a05c-383478ec9d15
    ...
    c482fbe1-9f16-4ae9-a05c-383478ec9dff
    c482fbe1-9f16-4ae9-a05c-383478ec9e00
    c482fbe1-9f16-4ae9-a05c-383478ec9e01
    

    with Guid like these, the number of different hashes generated is very small (256 different values), because the 3478ec9d/3478ec9e won't be hashed.

提交回复
热议问题