I read a very nice blog about ArrayPool<T>
and the benefits of using it for large objects. Of course I wanted to try it immediately! My example is not that fancy as the one shown in the blog though (the author uses BenchmarkDotNet
tests). However my test fails to show the same result and I am trying to understand the reason behind. Here is what I tried:
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}");
Here are the results for different array sizes:
// 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
As you can see something is terribly wrong here. As the 'Rent N' Return' operations seem to take almost constant time my best guess is that I don't force the Garbage collection correctly so I can measure the time taken to collect allocated
array from the heap (I need to include the GC.Collect()
time taken so it can be a fair fight).
Someone has any idea how to fix this example so it shows the expected result ?
Thanks in advance!