-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchArray.cs
More file actions
112 lines (90 loc) · 2.56 KB
/
SearchArray.cs
File metadata and controls
112 lines (90 loc) · 2.56 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
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
112
using System.Runtime.InteropServices.JavaScript;
using BenchmarkDotNet.Attributes;
namespace Benchmark;
[MemoryDiagnoser]
public class SearchArray
{
private List<TestClass> _testData;
private List<TestClass> _lookupData;
public SearchArray()
{
_testData = CreateData(1_000_000);
_lookupData = CreateData(100_000);
}
[Benchmark]
public void Contains()
{
var lookupDataInt = _lookupData
.Select(x => x.Id)
.ToArray();
for (int i = 0; i < _testData.Count - 1; i++)
{
if (lookupDataInt.Contains(_testData[i].Id))
_testData.RemoveAt(i);
}
}
[Benchmark]
public void HashSet()
{
var lookupDataInt = _lookupData
.Select(x => x.Id)
.ToHashSet();
for (int i = 0; i < _testData.Count - 1; i++)
{
if (lookupDataInt.Contains(_testData[i].Id))
_testData.RemoveAt(i);
}
}
[Benchmark]
public void Sort_BinarySearch()
{
var lookupDataInt = _lookupData
.Select(x => x.Id)
.ToArray();
Array.Sort(lookupDataInt);
for (int i = 0; i < _testData.Count - 1; i++)
{
if (Array.BinarySearch(lookupDataInt, _testData[i].Id) > 0)
_testData.RemoveAt(i);
}
}
[Benchmark]
public void Sort_BinarySearch_Span()
{
Span<int> lookupDataInt = _lookupData
.Select(x => x.Id)
.ToArray()
.AsSpan();
lookupDataInt.Sort();
for (int i = 0; i < _testData.Count - 1; i++)
{
if (lookupDataInt.BinarySearch(_testData[i].Id) > 0)
_testData.RemoveAt(i);
}
}
[Benchmark]
public void Sort_BinarySearch_Span_StackAlloc()
{
Span<int> lookupDataInt = stackalloc int[_lookupData.Count];
for (int i = 0; i < _lookupData.Count - 1; i++)
lookupDataInt[i] = _lookupData[i].Id;
lookupDataInt.Sort();
for (int i = 0; i < _testData.Count - 1; i++)
{
if (lookupDataInt.BinarySearch(_testData[i].Id) > 0)
_testData.RemoveAt(i);
}
}
private List<TestClass> CreateData(int nbItems)
{
Random rand = new Random(42);
return Enumerable.Range(1, nbItems)
.Select(x => new TestClass { Id = rand.Next(0, nbItems / 10) })
.ToList();
}
}
public class TestClass
{
public string Name { get; init; } = "Name";
public int Id { get; init; }
}