-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathListArrayBuilding.cs
62 lines (52 loc) · 1.36 KB
/
ListArrayBuilding.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
using BenchmarkDotNet.Attributes;
using DistIL.Attributes;
using System.Runtime.Intrinsics;
using System.Runtime.InteropServices;
[MemoryDiagnoser]
public class ListArrayBuilding
{
[Params(4, 1024)]
public int Count {
set {
_count = value;
_items = DynamicList_Gen();
}
}
int _count;
IReadOnlyList<int> _items;
[Benchmark]
public int[] DirectArray_Gen()
{
int count = _count;
var array = new int[count];
int seed = 12345;
// Note: JIT doesn't see that `count == array.Length`, won't eliminate bounds check for `i < count`
for (int i = 0; i < array.Length; i++) {
seed = (seed * 8121 + 28411) % 134456;
array[i] = seed;
}
return array;
}
[Benchmark]
public int[] DynamicList_Gen()
{
int count = _count;
var list = new List<int>();
int seed = 12345;
for (int i = 0; i < count; i++) {
seed = (seed * 8121 + 28411) % 134456;
list.Add(seed);
}
return list.ToArray();
}
[Benchmark]
public int[] DynamicList_Enumer()
{
var list = new List<int>();
// Note: intentionally downcasting to interface
foreach (int x in _items) {
list.Add(x * 3 / 5 + 1);
}
return list.ToArray();
}
}