c#中byte数组0x,C#的字节数组比较

I have two byte arrays in C# using .NET 3.0.

What is the "most efficient" way to compare whether the two byte arrays contains the same content for each element?

For example, byte array {0x1, 0x2} is the same as {0x1, 0x2}. But byte array {0x1, 0x2} and byte array {0x2, 0x1} are not the same.

解决方案

Well, you could use:

public static bool ByteArraysEqual(byte[] b1, byte[] b2)

{

if (b1 == b2) return true;

if (b1 == null || b2 == null) return false;

if (b1.Length != b2.Length) return false;

for (int i=0; i < b1.Length; i++)

{

if (b1[i] != b2[i]) return false;

}

return true;

}

(I normally use braces for everything, but I thought I'd experiment with this layout style just for a change...)

This has a few optimisations which SequenceEqual can't (or doesn't) perform - such as the up-front length check. Direct array access will also be a bit more efficient than using the enumerator.

Admittedly it's unlikely to make a significant difference in most cases...

You could possibly make it faster in unmanaged code by making it compare 32 or 64 bits at a time instead of 8 - but I wouldn't like to code that on the fly.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值