-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayIteration.cs
111 lines (93 loc) · 2.49 KB
/
ArrayIteration.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
namespace Benchmarkator.Collections.Iteration;
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class ArrayIteration
{
[Params(4096)]
public int Length;
private int[] _data = null!;
[GlobalSetup]
public void Setup()
{
_data = Enumerable.Range(0, Length).ToArray();
}
[Benchmark]
public int ForLoopAccessIndex()
{
var arr = _data;
var item = 0;
for (var i = 0; i < arr.Length; i++)
{
item = arr[i];
}
return item;
}
[Benchmark]
public unsafe int ForLoopAccessPtr()
{
var arr = _data;
var item = 0;
// to get value on given index, `i` is added to address of first item
// (`i` offsets pointer by size of `int*`)
fixed (int* a = &arr[0])
{
for (var i = 0; i < arr.Length; i++)
{
item = *(a + i);
}
}
return item;
}
[Benchmark]
public int ForLoopAccessRef()
{
var arr = _data;
var item = 0;
// to get value on given index, `i` is added to reference to first item
// (`i` offsets pointer by size of `ref int`)
ref var first = ref arr[0];
for (var i = 0; i < arr.Length; i++)
{
item = Unsafe.Add(ref first, i);
}
return item;
}
[Benchmark]
public unsafe int WhileLoopAccessPtr()
{
var arr = _data;
var item = 0;
// move `tmp` in array, from first to last address
// (pointer to `tmp` is moved to next field each iteration)
fixed (int* a = &arr[0])
{
var last = a + arr.Length;
var tmp = a;
while (tmp < last)
{
item = *tmp;
tmp += 1;
}
}
return item;
}
[Benchmark]
public int WhileLoopAccessRef()
{
var arr = _data;
var item = 0;
// move `temp` in array, from first to last reference
// (reference to `tmp` is moved to next field each iteration)
ref var temp = ref arr[0];
ref var last = ref arr[arr.Length - 1];
while (Unsafe.IsAddressLessThan(ref temp, ref last) || Unsafe.AreSame(ref temp, ref last))
{
item = temp;
temp = ref Unsafe.Add(ref temp, 1);
}
return item;
}
}