我一直在寻找返回由ArraySegment保持的偏移量和计数的段的方法。虽然ArraySegment保存完整的原始数组,但它只是用任何对段的更改反映到原始数组来限制它。 ArraySegment的问题或者说局限性在于,它不会作为一个整体返回段,而我必须遍历值。最好的方法是以整体形式返回段吗?
byte[] input = new byte[5]{1,2,3,4,5};
ArraySegment<byte> delimited = new ArraySegment<byte>(input,0,2);
byte[] segment = HERE I NEED SOMETHING THAT WILL RETURN THE SEGMENT i.e. [0,1,2]
最重要的一点是,段必须不是一个副本,而应该引用原始数组。如果对段进行任何更改,它们必须反映在原始数组中。
非常感谢任何提示,谢谢!
好的,我对digEmAll和Thomas的代码运行了一些基准测试,令我惊讶的是,这个代码比其他代码快得多。这正是我迫切需要的。以下是结果。
Construct Size Elements assigned Iterations Time
_______________________________________________________________________________
ArraySegmentWrapper 1500 1500 1000000 396.3 ms
Array.Copy 1500 1500 1000000 4389.04 ms
从差异性上可以看出,很明显我将使用ArraySegment的代码。以下是基准测试代码。请注意,这可能有些偏见,因为人们会争论为什么"new"被放在循环内部。我只是试图尽可能地重现我目前手头的情况,并尽量不移动太多代码来解决它。这让我今天过得很愉快!
namespace ArraySegmentWrapped
{
class Program
{
public static Stopwatch stopWatch = new Stopwatch();
public static TimeSpan span = new TimeSpan();
public static double totalTime = 0.0;
public static int iterations = 1000000;
static void Main(string[] args)
{
int size = 1500;
int startIndex = 0;
int endIndex = 1499;
byte[] array1 = new byte[size];
byte[] array2 = null;
for (int index = startIndex; index < size; index++)
{
array1[index] = (byte)index;
}
ArraySegmentWrapper<byte> arraySeg;
for (int index = 0; index < iterations; index++)
{
stopWatch.Start();
arraySeg = new ArraySegmentWrapper<byte>(array1, startIndex, endIndex);
stopWatch.Stop();
totalTime += stopWatch.Elapsed.TotalMilliseconds;
}
Console.WriteLine("ArraySegment:{0:F6}", totalTime / iterations);
stopWatch.Reset();
totalTime = 0.0;
for (int index = 0; index < iterations; index++)
{
stopWatch.Start();
array2 = new byte[endIndex - startIndex + 1];
Array.Copy(array1, startIndex, array2, 0, endIndex);
stopWatch.Stop();
totalTime += stopWatch.Elapsed.TotalMilliseconds;
}
Console.WriteLine("Array.Copy:{0:F6}", totalTime / iterations);
}
}
// Code for ArraySegmentWrapper goes here
}
访问基准测试(已更新) 所以,Thomas指出基准测试并表示访问简单数组比ArraySegment更快,他完全正确。但是digEmAll指出我应该在Release模式下进行测试(抱歉之前在debug模式下测试的错误),我将代码几乎保持不变(迭代次数减少了两个零-无法等待输出,抱歉),并对访问相同数量的元素进行了一些修改,下面是我得到的结果。
Construct Size Elements accessed Iterations Time
_______________________________________________________________________________
ArraySegmentWrapper 1500 1500 1000000 5268.3 ms
Array.Copy 1500 1500 1000000 4812.4 ms
结论是尽管通过 ArraySegments 访问非常快,但访问速度较慢。