-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathSingletonBenchmarks.cs
95 lines (79 loc) · 2.6 KB
/
SingletonBenchmarks.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
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace DesignPatternsInCSharp.Benchmarks
{
[MeanColumn]
[MemoryDiagnoser]
[RankColumn]
public class SingletonBenchmarks
{
private ParallelOptions _parallelOptions;
private List<string> _strings;
[GlobalSetup]
public void GlobalSetup()
{
_parallelOptions =
new ParallelOptions()
{
MaxDegreeOfParallelism = 3,
};
_strings = new List<string>() { "one", "two", "three" };
}
[Benchmark(Baseline = true)]
public void Naive()
{
var instances = new ConcurrentDictionary<Singleton.v1.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v1.Singleton.Instance, 0));
}
[Benchmark]
public void Locking()
{
var instances = new ConcurrentDictionary<Singleton.v2.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v2.Singleton.Instance, 0));
}
[Benchmark]
public void BetterLocking()
{
var instances = new ConcurrentDictionary<Singleton.v3.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v3.Singleton.Instance, 0));
}
[Benchmark]
public void LessLazy()
{
var instances = new ConcurrentDictionary<Singleton.v4.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v4.Singleton.Instance, 0));
}
[Benchmark]
public void NestedLazy()
{
var instances = new ConcurrentDictionary<Singleton.v5.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v5.Singleton.Instance, 0));
}
[Benchmark]
public void LazyOfT()
{
var instances = new ConcurrentDictionary<Singleton.v6.Singleton, byte>();
Parallel.ForEach(
_strings,
_parallelOptions,
_ => instances.TryAdd(Singleton.v6.Singleton.Instance, 0));
}
}
}