-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathAnyOnArray.cs
54 lines (46 loc) · 1.39 KB
/
AnyOnArray.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
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
namespace StructLinq.Benchmark
{
[MemoryDiagnoser]
public class AnyOnArray
{
private const int Count = 1000;
private readonly int[] array;
public AnyOnArray()
{
array = Enumerable.ToArray(Enumerable.Range(0, Count));
}
[Benchmark]
public bool For()
{
for (int i = 0; i < Count; i++)
{
if (array[i] >= Count / 2)
return true;
}
return false;
}
[Benchmark(Baseline = true)]
public bool Linq() => array.Any(x=> x >= Count / 2);
[Benchmark]
public bool StructLinq() => array.ToStructEnumerable().Any(x => x >= Count /2);
[Benchmark]
public bool StructLinqZeroAlloc() => array.ToStructEnumerable().Any(x => x >= Count /2, x=>x );
[Benchmark]
public bool StructLinqIFunctionZeroAlloc()
{
var func = new AllFunction();
return array.ToStructEnumerable().Any(ref func, x => x);
}
private struct AllFunction : IFunction<int, bool>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Eval(int element)
{
return element >= Count / 2;
}
}
}
}