Skip to content

Commit 291a9f4

Browse files
author
Alex Peck
committed
lock bench
1 parent c52bc23 commit 291a9f4

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

BitFaster.Caching.Benchmarks/BitFaster.Caching.Benchmarks.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFrameworks>net48;net6.0;net8.0</TargetFrameworks>
5+
<TargetFrameworks>net48;net6.0;net8.0;net9.0</TargetFrameworks>
66
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
77
<!-- https://stackoverflow.com/a/59916801/131345 -->
88
<IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+

2+
using System.Threading;
3+
using Benchly;
4+
using BenchmarkDotNet.Attributes;
5+
using BenchmarkDotNet.Jobs;
6+
7+
namespace BitFaster.Caching.Benchmarks
8+
{
9+
[SimpleJob(RuntimeMoniker.Net90)]
10+
[MemoryDiagnoser(displayGenColumns: false)]
11+
[HideColumns("Job", "Median", "RatioSD", "Alloc Ratio")]
12+
[ColumnChart(Title ="Try enter ({JOB})")]
13+
public class LockBench
14+
{
15+
private int _value;
16+
private readonly object monitorLock = new object();
17+
#if NET9_0_OR_GREATER
18+
private readonly Lock threadingLock = new Lock();
19+
#endif
20+
21+
[Benchmark(Baseline = true)]
22+
public void UseMonitor()
23+
{
24+
bool lockTaken = false;
25+
Monitor.TryEnter(monitorLock, ref lockTaken);
26+
27+
if (lockTaken)
28+
{
29+
try
30+
{
31+
_value++;
32+
}
33+
finally
34+
{
35+
if (lockTaken)
36+
{
37+
Monitor.Exit(monitorLock);
38+
}
39+
}
40+
}
41+
}
42+
43+
[Benchmark()]
44+
public void UseLock()
45+
{
46+
#if NET9_0_OR_GREATER
47+
if (threadingLock.TryEnter())
48+
{
49+
try
50+
{
51+
_value++;
52+
}
53+
finally
54+
{
55+
threadingLock.Exit();
56+
}
57+
}
58+
#endif
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)