用户gil建议生成此解决方案的不安全代码:
// Copyright (c) 2008-2013 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) {
if(a1==a2) return true;
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;
}
}
它对尽可能多的数组进行基于64位的比较.这取决于数组开始对齐qword这一事实.如果没有qword对齐,它就可以工作,只是速度不如qword对齐.
它比简单的for
循环快7个定时器.使用J#library与原来的for
循环相当.使用.SequenceEqual的运行速度大约慢七倍;我觉得只是因为它使用了IEnumerator.下一步.我认为基于LINQ的解决方案至少有那么慢或更糟.