Skip to content

Instantly share code, notes, and snippets.

@Neo-Ciber94
Created August 27, 2021 00:22
Show Gist options
  • Save Neo-Ciber94/d48a563132981486d3ee1a6bd85768b7 to your computer and use it in GitHub Desktop.
Save Neo-Ciber94/d48a563132981486d3ee1a6bd85768b7 to your computer and use it in GitHub Desktop.
List.ToArray() vs Get underlying list array
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
namespace Benchmarks
{
[MemoryDiagnoser]
[ShortRunJob]
public class ToArrayVsTakeArrayBenchmark
{
[Params(64, 128, 256, 512)]
public int Max { get; set; }
[Benchmark(Baseline = true)]
public Span<int> ToArray()
{
var list = new List<int>();
for (var i = 0; i < Max; i++)
{
list.Add(i);
}
return list.ToArray();
}
[Benchmark]
public Span<int> TakeArray()
{
var list = new List<int>();
for (var i = 0; i < Max; i++)
{
list.Add(i);
}
return CollectionsMarshal.AsSpan(list);
}
[Benchmark]
public Span<int> ToArrayWithInitialCapacity()
{
// Half to force reallocation
var list = new List<int>(Max / 2);
for (var i = 0; i < Max; i++)
{
list.Add(i);
}
return list.ToArray();
}
[Benchmark]
public Span<int> TakeArrayWithInitialCapacity()
{
// Half to force reallocation
var list = new List<int>(Max / 2);
for (var i = 0; i < Max; i++)
{
list.Add(i);
}
return CollectionsMarshal.AsSpan(list);
}
}
}
@Neo-Ciber94
Copy link
Author

Results:

Method Max Mean Error StdDev Ratio RatioSD Gen 0 Gen 1 Gen 2 Allocated
ToArray 64 365.3 ns 679.83 ns 37.26 ns 1.00 0.00 0.2217 - - 928 B
TakeArray 64 373.6 ns 488.58 ns 26.78 ns 1.03 0.16 0.1545 - - 648 B
ToArrayWithInitialCapacity 64 290.3 ns 347.33 ns 19.04 ns 0.80 0.06 0.1779 - - 744 B
TakeArrayWithInitialCapacity 64 247.9 ns 270.54 ns 14.83 ns 0.68 0.03 0.1106 - - 464 B
ToArray 128 741.2 ns 288.36 ns 15.81 ns 1.00 0.00 0.4110 - - 1720 B
TakeArray 128 629.0 ns 576.28 ns 31.59 ns 0.85 0.04 0.2823 - - 1184 B
ToArrayWithInitialCapacity 128 502.2 ns 427.99 ns 23.46 ns 0.68 0.04 0.3300 - - 1384 B
TakeArrayWithInitialCapacity 128 420.8 ns 27.06 ns 1.48 ns 0.57 0.01 0.2027 - - 848 B
ToArray 256 1,453.5 ns 1,499.73 ns 82.21 ns 1.00 0.00 0.7839 - - 3280 B
TakeArray 256 1,117.7 ns 1,342.71 ns 73.60 ns 0.77 0.07 0.5322 - - 2232 B
ToArrayWithInitialCapacity 256 948.8 ns 576.27 ns 31.59 ns 0.65 0.03 0.6351 - - 2664 B
TakeArrayWithInitialCapacity 256 775.4 ns 701.59 ns 38.46 ns 0.54 0.06 0.3862 - - 1616 B
ToArray 512 2,360.1 ns 1,180.88 ns 64.73 ns 1.00 0.00 1.5221 - - 6376 B
TakeArray 512 2,162.8 ns 705.05 ns 38.65 ns 0.92 0.02 1.0262 - - 4304 B
ToArrayWithInitialCapacity 512 1,897.1 ns 738.74 ns 40.49 ns 0.80 0.02 1.2474 - - 5224 B
TakeArrayWithInitialCapacity 512 1,598.0 ns 2,882.06 ns 157.98 ns 0.68 0.07 0.7534 - - 3152 B

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment