I've heard rumours that lock is "slow" but never tried to measure its performance myself until now. What would be the right way to benchmark it? I use the code below which produces consistent results, but I'm still not sure if I do it correctly.
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<ClassUnderTest>();
}
}
[Config(typeof(Config))]
public class ClassUnderTest
{
private class Config : ManualConfig
{
public Config()
{
Add(Job.LegacyJitX64);
Add(MarkdownExporter.StackOverflow);
}
}
private readonly object _o = new object();
public decimal Money;
[Setup]
public void SetupData()
{
Money = 0;
}
[Benchmark(Baseline = true)]
public decimal NoLock()
{
return ++Money;
}
[Benchmark]
public decimal Lock()
{
lock (_o)
{
return ++Money;
}
}
}
Results:
Host Process Environment Information:
BenchmarkDotNet=v0.9.8.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4790 CPU 3.60GHz, ProcessorCount=8
Frequency=3507519 ticks, Resolution=285.1018 ns, Timer=ACPI
CLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1055.0
Type=ClassUnderTest Mode=Throughput Platform=X64
Jit=LegacyJit GarbageCollection=Concurrent Workstation
Method | Median | StdDev | Scaled |
------- |----------- |---------- |------- |
NoLock | 22.7166 ns | 0.1533 ns | 1.00 |
Lock | 38.0836 ns | 0.2947 ns | 1.68 |