网站开发培训流程,网站公司企业宗旨,怎么办网站平台,动漫网页设计代码咨询区 Hafthor#xff1a;我现在业务中遇到了一个场景#xff1a;如何简洁高效的判断两个 byte[] 的相等性#xff1f;我现在是这么实现的#xff0c;有一点繁琐#xff1a;static bool ByteArrayCompare(byte[] a1, byte[] a2)
{if (a1.Length ! a2.Length)return false… 咨询区 Hafthor我现在业务中遇到了一个场景如何简洁高效的判断两个 byte[] 的相等性我现在是这么实现的有一点繁琐
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{if (a1.Length ! a2.Length)return false;for (int i0; ia1.Length; i)if (a1[i]!a2[i])return false;return true;
}在 java 中是可以非常方便的实现。
java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2);回答区 aku其实你可以使用 Linq 提供的 Enumerable.SequenceEqual 扩展方法达到同样的快捷效果。
using System;
using System.Linq;
...
var a1 new int[] { 1, 2, 3};
var a2 new int[] { 1, 2, 3};
var a3 new int[] { 1, 2, 4};
var x a1.SequenceEqual(a2); // true
var y a1.SequenceEqual(a3); // false顺便提醒一下编译器和运行时 会优化这种 loop 循环所以你不需要担心什么性能问题。plinth可以借助 Windows 自带的系统函数帮你搞定你要做的就是用 P/Invoke 调它参考代码如下
[DllImport(msvcrt.dll, CallingConventionCallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, long count);static bool ByteArrayCompare(byte[] b1, byte[] b2)
{// Validate buffers are the same length.// This also ensures that the count does not exceed the length of either buffer. return b1.Length b2.Length memcmp(b1, b2, b1.Length) 0;
}或者你可以自己封装一段 unsafe 的代码。
// 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(a1a2) return true;if(a1null || a2null || a1.Length!a2.Length)return false;fixed (byte* p1a1, p2a2) {byte* x1p1, x2p2;int l a1.Length;for (int i0; i l/8; i, x18, x28)if (*((long*)x1) ! *((long*)x2)) return false;if ((l 4)!0) { if (*((int*)x1)!*((int*)x2)) return false; x14; x24; }if ((l 2)!0) { if (*((short*)x1)!*((short*)x2)) return false; x12; x22; }if ((l 1)!0) if (*((byte*)x1) ! *((byte*)x2)) return false;return true;}
}点评区 plinth 大佬的想法别出心裁借助现存强大的 Windows 系统函数免去了很多重复的业务逻辑简单粗暴又高效学习了。