Span<T>.SequenceEquals is faster than memcmp
Published on: 2025-05-23 13:53:33
2025-03-30 What's faster than Memcmp?
In this post I look at improvements in .NET and using Span for performance and portability.
I was examining portability issues in a code base that I wanted to migrate from .NET framework 4.8.1 to .NET8. I discovered use of msvcrt.dll . I quickly established it is a popular stackoverflow answer for a fast way to compare byte arrays in .NET
The answer as provided, and faithfully copied into codebases, is this:
[ DllImport ( "msvcrt.dll" , CallingConvention = CallingConvention . Cdecl )] static extern int memcmp ( byte [] b1 , byte [] b2 , long count ); static bool ByteArrayCompare ( byte [] b1 , byte [] b2 ) { // Validate buffers are the same length. // This also ensures that the count does not exceed the length of either buffer. return b1 . Length == b2 . Length && memcmp ( b1 , b2 , b1 . Length ) == 0 ; }
A big performance improvement in modern .NET is the Span type. The documentation describes it as:
Provides a type-safe and memory-safe r
... Read full article.