Repository navigation
Fix Guid's GetHashCode to work better (not ignore parts of it) - #5191
Conversation
A common pattern is that the last bits of the GUID are the most unique, however our current hash code ignores most of them. Fix this to simply XOR all bits in the GUID 32 bits at a time. This is more efficient and a better hash than what we have currently.
|
@dotnet-bot Ubuntu x64 Checked Build and Test |
|
👍 |
| { | ||
| return _a ^ (((int)_b << 16) | (int)(ushort)_c) ^ (((int)_f << 24) | _k); | ||
| // Simply XOR all the bits of the GUID 32 bits at a time. | ||
| fixed (int* ptr = &this._a) |
There was a problem hiding this comment.
Would it be better to make a copy of the struct instead of using fixed? e.g.
Guid self = this;
int* addr = &self._a;
return addr[0] ^ addr[1] ^ addr[2] ^ addr[3];I found while working on a previous PR that the jit would not inline methods (even short ones) with fixed, so maybe this will help the method inline. Additionally, it could theoretically remove the additional copy if the Guid is not a member of a class, although that may face complications since we take the copy's address.
There was a problem hiding this comment.
It is an interesting idea, but it is unclear which is better. You need to set up a microbenchmark of a Dictionary<Guid, T> and see if it actually wins. If it does, we can change it.
|
FWIW I will probably work on removing the |
|
@AndyAyersMS Awesome. Will be interesting to see if the performance improves after your changes. .. of course there is still the overhead of fixed itself, and I'm not quite sure how expensive that is, but we avoid a copy at the very least. |
|
Just FYI, the overhead of the fixed statement is very cheap (basically you have to set a local variable slot to the value being pinned, which is 1 instruction). However it probably inhibits a range of optimizations (like inlining), not because there is a true problem, but because it is JIT work to do it, and fixed statements are rare. For what it is worth... |
…t/coreclr#5191) A common pattern is that the last bits of the GUID are the most unique, however our current hash code ignores most of them. Fix this to simply XOR all bits in the GUID 32 bits at a time. This is more efficient and a better hash than what we have currently. Commit migrated from dotnet/coreclr@a22c755
A common pattern is that the last bits of the GUID are the most unique, however our current hash code ignores most of them (only 6 of the last 8 bytes are ignored). Fix this by simply XOR all bits in the GUID 32 bits at a time. This is more efficient and a better hash than what we have currently.
This is not a theoretical problem. Users in OSG had a large dictionary indexed by GUID and had a scenario that took 60 seconds and using a good hash code reduced it to 200msec.
This does use unsafe code but we already have unsafe code elsewhere in guid.cs. We could decide to have union fields to avoid the unsafe code but this is a smaller delta.