-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathArrayOfClassSum.cs
87 lines (75 loc) · 2.23 KB
/
ArrayOfClassSum.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
76
77
78
79
80
81
82
83
84
85
86
87
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using StructLinq.Array;
namespace StructLinq.Benchmark
{
[MemoryDiagnoser]
public class ArrayOfClassSum
{
private const int Count = 1000;
private readonly Container[] array;
public ArrayOfClassSum()
{
array = Enumerable.Range(0, Count).Select(x => new Container(x)).ToArray();
}
[Benchmark]
public int Handmaded()
{
int sum = 0;
for (int i = 0; i < Count; i++)
{
sum += array[i].Element;
}
return sum;
}
[Benchmark(Baseline = true)]
public int LINQSum() => array.Select(x => x.Element).Sum();
[Benchmark]
public int StructLinq()
{
return array.ToStructEnumerable()
.Select(x=> x.Element)
.Sum();
}
[Benchmark]
public int StructLinqWithVisitor()
{
return array.ToStructEnumerable()
.Select(x=> x.Element, x => (IStructEnumerable<Container, ArrayStructEnumerator<Container>>) x)
.Sum();
}
[Benchmark]
public int StructLinqZeroAlloc()
{
var @select = new ContainerSelect();
return array.ToStructEnumerable()
.Select(ref @select, x=>x, x=>x)
.Sum(x => x);
}
[Benchmark]
public int StructLinqZeroAllocWithVisitor()
{
var @select = new ContainerSelect();
return array.ToStructEnumerable()
.Select(ref @select, x => (IStructEnumerable<Container, ArrayStructEnumerator<Container>>) x, x => x)
.Sum(x => x);
}
}
public class Container
{
public readonly int Element;
public Container(int element)
{
Element = element;
}
}
internal struct ContainerSelect : IFunction<Container, int>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int Eval(Container element)
{
return element.Element;
}
}
}