Created
February 25, 2020 16:44
-
-
Save ermau/1adc27f729fa5eb8e17cc47b71eb3317 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18363 | |
Intel Core i7-6950X CPU 3.00GHz (Skylake), 1 CPU, 20 logical and 10 physical cores | |
[Host] : .NET Framework 4.8 (4.8.4121.0), X86 LegacyJIT | |
DefaultJob : .NET Framework 4.8 (4.8.4121.0), X86 LegacyJIT | |
| Method | Mean | Error | StdDev | | |
|-------------- |---------:|---------:|---------:| | |
| LockTryGetSet | 28.42 ns | 0.006 ns | 0.006 ns | | |
| LockTryGet | 28.33 ns | 0.012 ns | 0.010 ns | | |
| CDTryGetSet | 15.78 ns | 0.001 ns | 0.001 ns | | |
| CDTryGet | 13.75 ns | 0.006 ns | 0.005 ns | | |
*/ | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace TestConcurrentCollectionPerf | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run (typeof(LockVsConcurrentDictionary)); | |
} | |
} | |
public class LockVsConcurrentDictionary | |
{ | |
[GlobalSetup] | |
public void Setup () | |
{ | |
this.values = new Dictionary<int, string> { | |
{ 1, "test1" }, | |
{ 2000, "test2" } | |
}; | |
this.cvalues = new ConcurrentDictionary<int, string> (); | |
this.cvalues[1] = "test1"; | |
this.cvalues[2000] = "test2"; | |
} | |
[Benchmark] | |
public void LockTryGetSet () | |
{ | |
lock (this.sync) { | |
if (!this.values.TryGetValue (3000, out string value)) | |
this.values[3000] = "value"; | |
} | |
} | |
[Benchmark] | |
public void LockTryGet () | |
{ | |
lock (this.sync) { | |
this.values.TryGetValue (2000, out string value); | |
} | |
} | |
[Benchmark] | |
public void CDTryGetSet () | |
{ | |
this.cvalues.GetOrAdd (3000, (k) => "value"); | |
} | |
[Benchmark] | |
public void CDTryGet () | |
{ | |
this.cvalues.TryGetValue (2000, out string value); | |
} | |
private ConcurrentDictionary<int, string> cvalues; | |
private Dictionary<int, string> values; | |
private readonly object sync = new object(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment