-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathToArrayComparison.cs
75 lines (66 loc) · 2.02 KB
/
ToArrayComparison.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using StructLinq.Range;
using StructLinq.Utils.Collections;
namespace StructLinq.Benchmark
{
[MemoryDiagnoser]
[SimpleJob(RuntimeMoniker.Net48, baseline: true)]
[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.Net70)]
public class ToArrayComparison
{
private RangeEnumerable enumerable;
public ToArrayComparison()
{
enumerable = StructEnumerable.Range(0, 10_000);
}
[Benchmark]
public int[] ToListThenToArray()
{
var list = new List<int>();
foreach (var i in enumerable)
{
list.Add(i);
}
return list.ToArray();
}
[Benchmark]
public int[] ToPooledListThenToArray()
{
var list = new PooledList<int>(0, ArrayPool<int>.Shared);
var enumerator = enumerable.GetEnumerator();
PoolLists.Fill(ref list, ref enumerator);
var array = list.ToArray();
list.Dispose();
return array;
}
[Benchmark]
public int[] UseCountForToArray()
{
var enumerator = enumerable.GetEnumerator();
return ToArray<int, RangeEnumerator>(ref enumerator, enumerable.Count);
}
[Benchmark]
public int[] StructLinqToArray()
{
return enumerable.ToArray(x => x);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static T[] ToArray<T, TEnumerator>(ref TEnumerator enumerator, int size)
where TEnumerator : struct, IStructEnumerator<T>
{
var result = new T[size];
var i = 0;
while (enumerator.MoveNext())
{
result[i++] = enumerator.Current;
}
enumerator.Dispose();
return result;
}
}
}