-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathForEach.cs
More file actions
74 lines (64 loc) · 1.79 KB
/
ForEach.cs
File metadata and controls
74 lines (64 loc) · 1.79 KB
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
using System;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace StructLinq.Benchmark
{
[MemoryDiagnoser]
public class ForEach
{
private int count;
private Action<int> action;
private const int Count = 100000;
public ForEach()
{
count = 0;
action = i => count++;
}
[Benchmark(Baseline = true)]
public int ClrForEach()
{
var sysRange = Enumerable.Range(0, Count);
foreach (var i in sysRange)
{
count++;
}
return count;
}
[Benchmark]
public int WithAction()
{
StructEnumerable.Range(0, Count).ForEach(action);
return count;
}
[Benchmark]
public int WithStruct()
{
CountAction<int> countAction = new CountAction<int> { Count = 0 };
StructEnumerable.Range(0, Count).ForEach(ref countAction);
return countAction.Count;
}
[Benchmark]
public int ZeroAllocWithStruct()
{
CountAction<int> countAction = new CountAction<int> { Count = 0 };
StructEnumerable.Range(0, Count).ForEach(ref countAction, x=> x);
return countAction.Count;
}
[Benchmark]
public int ToTypedEnumerableWithStruct()
{
CountAction<int> countAction = new CountAction<int> { Count = 0 };
var convertRange = Enumerable.Range(0, Count).ToStructEnumerable();
convertRange.ForEach(ref countAction);
return countAction.Count;
}
}
struct CountAction<T> : IAction<T>
{
public int Count;
public void Do(T element)
{
Count++;
}
}
}