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<T> type. The documentation describes it as: Provides a type-safe and memory-safe representation of a contiguous region of arbitrary memory. That's not a super helpful description, but the summary is that it's stack-allocated rather than heap allocated. Span<T> has an extension method SequenceEqual<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> other), and we'll see how it fares. public static bool EqualsSpan(ReadOnlySpan<byte> b1, ReadOnlySpan<byte> b2) { return b1.SequenceEqual(b2); } Let's see how it stacks up against a couple of naive implementations, a for loop and using Enumerable.SequenceEquals: public static bool EqualsLoop(byte[] b1, byte[] b2) { if (b1.Length != b2.Length) return false; for (int i = 0; i < b1.Length; i++) { if (b1[i] != b2[i]) return false; } return true; } public static bool EqualsSequenceEqual(byte[] b1, byte[] b2) { return b1.SequenceEqual(b2); } We compare using two identical arrays since this is typically the worst-case for equality checking, and we're going to benchmark on a range of array sizes: 10 bytes, 1KB, 1MB and 1GB. [Params(10, 1_024, 1_048_576, 1073741824)] public in...
First seen: 2025-03-30 17:34
Last seen: 2025-03-31 04:39