【发布时间】:2023-04-04 01:06:02
【问题描述】:
我优化了一个扩展方法来比较两个流的相等性(字节对字节) - 知道这是一种热门方法,我尝试尽可能优化它(流可以达到数兆字节的长度)。我基本上想出了以下方法:
[StructLayout(LayoutKind.Explicit)]
struct Converter
{
[FieldOffset(0)]
public Byte[] Byte;
[FieldOffset(0)]
public UInt64[] UInt64;
}
/// <summary>
/// Compares two streams for byte-by-byte equality.
/// </summary>
/// <param name="target">The target stream.</param>
/// <param name="compareTo">The stream to compare the target to.</param>
/// <returns>A value indicating whether the two streams are identical.</returns>
public static bool CompareBytes(this Stream target, Stream compareTo)
{
if (target == null && compareTo == null)
return true;
if (target == null || compareTo == null)
return false;
if (target.Length != compareTo.Length)
return false;
if (object.ReferenceEquals(target, compareTo))
return true;
if (!target.CanRead || !target.CanSeek)
throw new ArgumentOutOfRangeException("target");
if (!compareTo.CanRead || !compareTo.CanSeek)
throw new ArgumentOutOfRangeException("target");
lock (target)
{
lock (compareTo)
{
var origa = target.Position;
var origb = compareTo.Position;
try
{
target.Position = compareTo.Position = 0;
// Shrink the number of comparisons.
var arr1 = new byte[4096];
var convert1 = new Converter() { Byte = arr1 };
var arr2 = new byte[4096];
var convert2 = new Converter() { Byte = arr2 };
int len;
while ((len = target.Read(arr1, 0, 4096)) != 0)
{
if (compareTo.Read(arr2, 0, 4096) != len)
return false;
for (var i = 0; i < (len / 8) + 1; i++)
if (convert1.UInt64[i] != convert2.UInt64[i])
return false;
}
return true;
}
finally
{
target.Position = origa;
compareTo.Position = origb;
}
}
}
}
问题是convert1.UInt64[i] != convert2.UInt64[i]if 块(返回false)正在被评估,即使值相等。我分别检查了每个,然后检查了“不等于”的结果。 我完全不相信:
我没有弄乱指令指针——这就是代码的执行方式和监视引脚的运行方式。
有什么想法会发生这种情况吗?
【问题讨论】:
-
看起来像是在进行参考比较(不同的对象,始终为假)而不是值比较
-
我很困惑,两个struct属性的FieldOffset都为0,你怎么知道你在比较苹果和苹果?
-
@mtijn 见this thread。数组将占用相同的内存空间 - 因此写入其中一个将更新另一个。
标签: c# logic conditional