Last active
August 7, 2022 05:11
-
-
Save Hafthor/6800165 to your computer and use it in GitHub Desktop.
Fast compare for byte arrays in .NET - uses unsafe code to compare by casting as longs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2008-2022 Hafthor Stefansson | |
// Distributed under the MIT/X11 software license | |
// Ref: http://www.opensource.org/licenses/mit-license.php. | |
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) { | |
unchecked { | |
if(a1==null || a2==null || a1.Length!=a2.Length) | |
return false; | |
fixed (byte* p1=a1, p2=a2) { | |
byte* x1=p1, x2=p2; | |
int l = a1.Length; | |
for (int i=0; i < l/8; i++, x1+=8, x2+=8) | |
if (*((long*)x1) != *((long*)x2)) return false; | |
if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; } | |
if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; } | |
if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false; | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment