Guid comparer using x86 SIMD instructions #73252
Replies: 2 comments 1 reply
-
You don't need to save constant vectors to static fields - moreover, it makes code only slower now. From my understand |
Beta Was this translation helpful? Give feedback.
-
What an awesome display of your intellectual integrity, I hope the bits treat you well, maybe the sound of shuffling bytes leads you the way, to the miracle of that the 128bits create, friend, SIMD is one the most powerful weapon on this planet a human can have inside .NET, aside from source generation custom Json serializer a working encryption implementation IAsyncEnumerable helper object mappers, it will pays you off down the road |
Beta Was this translation helpful? Give feedback.
-
I wrote a
Guid
comparer that uses x86 SIMD instructions to implement a branchless comparer.The existing guid comparison (
Guid.CompareTo
) is fast enough, as it usually only has to inspect a single value to make a determination. However, in some benchmarking, it seems like it might suffer from branch misprediction. In a fully-random guid the first compared value will be random, so the branch is going to be unpredictable. In my benchmarking, I found the SIMD approach to be ~2x faster (half the time) as the current comparer implementation, when comparing random guids.The more interesting case is when doing comparisons of "sequential guids", such as those produced by
UuidCreateSequential
on Windows. Using the standard guid comparer, the fastest changing byte in a sequential guid is also the first byte compared by the standard guid comparer. Comparing pairs of sequentially allocated guids, the standard comparer is marginally faster than the SIMD implementation, since the first branch becomes very predictable. The SIMD compare was 21% slower.However, when using SqlGuid to do the comparison, the fastest changing byte is the last byte compared. SqlGuid uses a comparer which will match the order produced by SqlServer
order by
. This means that if you were trying to sort sequential guids in .NET using the SqlGuid comparer, it is going to be a bit slower than sorting random guids, as most of the guid bytes will compare equal. In this scenario I found the SIMD approach to be ~5x faster than theSqlGuid
comparer. Given the changes might be coming in #72549, this might not be as dramatic, but I think it would still be significant.The only thing that needs to change between the Guid and SqlGuid comparison implementations is the Shuffle vector, see commented out line.
It is entirely possible there is a flaw in my logic, but it agreed with the existing comparer in all the testing I did. Maybe someone can see some improvements, as I'm definitely not an expert in SIMD operations.
Beta Was this translation helpful? Give feedback.
All reactions