Skip to content

Instantly share code, notes, and snippets.

@jiulongw
Created September 14, 2014 20:34
Show Gist options
  • Save jiulongw/9aac2d87eecf4b6d3ff9 to your computer and use it in GitHub Desktop.
Save jiulongw/9aac2d87eecf4b6d3ff9 to your computer and use it in GitHub Desktop.
Fast Byte Array Compare
/// <summary>
/// Compare if given two byte arrays are identical.
/// </summary>
/// <param name="x">byte array to compare.</param>
/// <param name="y">byte array to compare.</param>
/// <returns>true if x and y are identical.</returns>
public unsafe static bool ByteArrayCompare(byte[] x, byte[] y)
{
if (x == null || y == null || x.Length != y.Length)
{
return false;
}
fixed (byte* px = x, py = y)
{
byte* ex = px, ey = py;
int l = x.Length;
for (int i = 0; i < l / 8; i++, ex += 8, ey += 8)
{
if (*((long*)ex) != *((long*)ey))
{
return false;
}
}
if ((l & 4) != 0)
{
if (*((int*)ex) != *((int*)ey))
{
return false;
}
ex += 4;
ey += 4;
}
if ((l & 2) != 0)
{
if (*((short*)ex) != *((short*)ey))
{
return false;
}
ex += 2;
ey += 2;
}
if ((l & 1) != 0)
{
if (*ex != *ey)
{
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment