没有绑定检查的C#byte []比较

sho*_*tsy 6 c# arrays comparison performance byte

我正在寻找性能有效的方法来比较两个字节[]的相等性.大小超过1 MB,因此应尽量减少每个数组元素的开销.

我的目标是通过避免两个数组的重复绑定检查来击败每个项目的速度SequenceEqual手动编码的for循环.以同样的方式导致快速,会导致什么?Array.Copymemcpymemcmp

Guf*_*ffa 16

您可以使用不安全的代码来执行指针操作.您可以将四个字节一次比较为整数:

public static bool ArrayCompare(byte[] a, byte[] b) {
  if (a.Length != b.Length) return false;
  int len = a.Length;
  unsafe {
    fixed(byte* ap = a, bp = b) {
      int* aip = (int*)ap, bip = (int*)bp;
      for (;len >= 4;len-=4) {
        if (*aip != *bip) return false;
        aip++;
        bip++;
      }
      byte* ap2 = (byte*)aip, bp2 = (byte*)bip;
      for (;len>0;len--) {
        if (*ap2 != *bp2) return false;
        ap2++;
        bp2++;
      }
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

A对一个简单的循环进行了测试,速度提高了大约六倍.

正如Josh Einstein所建议的那样,long可以用在64位系统上.实际上它在32位和64位系统上似乎几乎快了两倍:

public static bool ArrayCompare64(byte[] a, byte[] b) {
  if (a.Length != b.Length) return false;
  int len = a.Length;
  unsafe {
    fixed (byte* ap = a, bp = b) {
      long* alp = (long*)ap, blp = (long*)bp;
      for (; len >= 8; len -= 8) {
        if (*alp != *blp) return false;
        alp++;
        blp++;
      }
      byte* ap2 = (byte*)alp, bp2 = (byte*)blp;
      for (; len > 0; len--) {
        if (*ap2 != *bp2) return false;
        ap2++;
        bp2++;
      }
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)


Han*_*ant 12

如果性能真的很重要,那么最快的方法是使用每个Windows版本附带的CRT库.这个代码在我的poky笔记本电脑上需要大约51毫秒,也适用于64位机器:

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

class Program {
  static void Main(string[] args) {
    byte[] arr1 = new byte[50 * 1024 * 1024];
    byte[] arr2 = new byte[50 * 1024 * 1024];
    var sw = Stopwatch.StartNew();
    bool equal = memcmp(arr1, arr2, arr1.Length) == 0;
    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds);
    Console.ReadLine();
  }
  [DllImport("msvcrt.dll")]
  private static extern int memcmp(byte[] arr1, byte[] arr2, int cnt);
}
Run Code Online (Sandbox Code Playgroud)