C#byte []比较无边界检查 [英] C# byte[] comparison without bound checks

查看:151
本文介绍了C#byte []比较无边界检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找性能有效的方法来比较两个字节[]的相等。大小高于1 MB,因此每个数组元素的开销应该最小化。

I am looking for performance efficient ways to compare two byte[] for equality. Sizes are above 1 MB, so the overhead for each array element should be minimized.

我的目标是击败 SequenceEqual 手动编码每个项目的循环避免对两个数组的重复绑定检查。以同样的方式, Array.Copy 可能导致快速 memcpy ,会导致 memcmp

I aim to beat the speeds of SequenceEqual or a hand-coded for-loop over every item, by avoiding the repetitive bound checks for both arrays. In the same way that Array.Copy could lead to fast memcpy, what will lead to a memcmp?

推荐答案

如果性能真的很重要,那么最快的方法是使用CRT库包括每个版本的Windows。这个代码在我的poky笔记本电脑上花了〜51毫秒,也在64位机器上工作:

If performance really matters then the fastest way to do it is by using the CRT library included with every version of Windows. This code takes ~51 msec on my poky laptop, works on 64-bit machines too:

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);
}

这篇关于C#byte []比较无边界检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆