C# 与x27之间的时间比较;ArrayPool<;T>;。共有租金';和';新T[]和#x27;

C# 与x27之间的时间比较;ArrayPool<;T>;。共有租金';和';新T[]和#x27;,c#,C#,我读了一篇关于ArrayPool的非常好的文章,以及将它用于大型对象的好处。我当然想马上试试!不过,我的例子并不像博客中所展示的那样奇特(作者使用了BenchmarkDotNettests)。然而,我的测试没有显示出同样的结果,我正在努力理解背后的原因。以下是我尝试过的: var _Pool = ArrayPool<int>.Shared; var sizeToAllocate = 100_000; Stopwatch sw = new Stopwatch(); sw.Start

我读了一篇关于
ArrayPool
的非常好的文章,以及将它用于大型对象的好处。我当然想马上试试!不过,我的例子并不像博客中所展示的那样奇特(作者使用了
BenchmarkDotNet
tests)。然而,我的测试没有显示出同样的结果,我正在努力理解背后的原因。以下是我尝试过的:

var _Pool = ArrayPool<int>.Shared;

var sizeToAllocate = 100_000;
Stopwatch sw = new Stopwatch();

sw.Start();
var rentAndRetur = _Pool.Rent(sizeToAllocate);
_Pool.Return(rentAndRetur);
sw.Stop();
Console.WriteLine($"Using 'Rent' + cleared with 'Return':   {sw.Elapsed}");

sw.Reset();

sw.Start();
var allocated = new int[sizeToAllocate];
allocated = null; //make sure 'allocated' is set to null so the GC can collct the allocated memory
GC.Collect(3, GCCollectionMode.Forced, true); // the size of the array > 85 000 bytes which means the LOH should be used for allocation (param 3 should be correct for LOH Gen)
sw.Stop();
Console.WriteLine($"Allocated with 'new' + GC collected:    {sw.Elapsed}");
正如你所看到的,这里有严重的问题。由于“Rent N”Return”操作花费的时间几乎是恒定的,因此我最好的猜测是,我没有正确地强制垃圾收集,因此我可以测量从堆中收集
分配的
数组所花费的时间(我需要包括
GC.collect()
所花费的时间,以便公平地进行斗争)。 有人知道如何修复此示例,从而显示预期结果吗?
提前谢谢

你不能指望秒表能够可靠地测量性能,尤其是像这里这样的亚毫秒时间。请在循环中尝试它,例如10000次,然后仅在循环完成后收集。我不确定
.Return
是否清除数组。我想不是。因此,您可能不会将GC包括在测试中。但要计算执行的集合数量。最好的方法是Benchmark.NET。花些时间理解Benchmark.NET,并重写您的基准以使用它。这是一种标准工具,而秒表则极不可靠。
// size: 10 000
// Using 'Rent' + cleared with 'Return':   00:00:00.0006801
// Allocated with 'new' + GC collected:    00:00:00.0001328

// size 100 000
// Using 'Rent' + cleared with 'Return':   00:00:00.0006803
// Allocated with 'new' + GC collected:    00:00:00.0001088

// size: 1 000 000
// Using 'Rent' + cleared with 'Return':   00:00:00.0007203
// Allocated with 'new' + GC collected:    00:00:00.0006110