-
-
Save Neo-Ciber94/d48a563132981486d3ee1a6bd85768b7 to your computer and use it in GitHub Desktop.
List.ToArray() vs Get underlying list array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results: