I'm trying to compare 2 byte array using pointers. I treat the byte arrays as int pointer to run things faster(compare 4 bytes together).
public static bool DoBuffersEqual(byte[] first, byte[] second)
{
unsafe
{
fixed (byte* pfirst = first, psecond = second)
{
int* intfirst = (int*)pfirst;
int* intsecond = (int*)psecond;
for (int i = 0; i < first.Length / 4; i++)
{
if ((intfirst + i) != (intsecond + i))
return false;
}
}
}
return true;
}
private void Form1_Load(object sender, EventArgs e)
{
byte[] arr1 = new byte[4000];
byte[] arr2 = new byte[4000];
for (int i = 0; i < arr1.Length; i++)
{
arr1[i] = 100;
arr2[i] = 100;
}
bool res = DoBuffersEqual(arr1, arr2);
Console.WriteLine(res);
}
For some reason i'm getting False result after calling this function...
Does anybody have any idea what's wrong here?
Thanks in advance!
if (*(intfirst + i) != *(intsecond + i))Vector<byte>and SIMD, so that on modern CPUs you can compare much wider chunks at a time (32 bytes = 256 bits on my AVX i7). The tricky bit is loading the values -Unsafe.Read<T>is your friend there. Also, remember to checkVector.IsHardwareAccelerated- if it isfalse, don't use it; and checkVector<byte>.Countto check the local hardware-specific SIMD support to know your stride size. And even if you don't like SIMD: you can still have the op-count by usinglongrather thanint.