Skip to content

Instantly share code, notes, and snippets.

@bgrainger
Created August 19, 2020 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgrainger/878ccdb3ccdcd434c4218cee4e61ffea to your computer and use it in GitHub Desktop.
Save bgrainger/878ccdb3ccdcd434c4218cee4e61ffea to your computer and use it in GitHub Desktop.
static readonly object s_lock = new object();
static readonly SemaphoreSlim s_semaphore = new SemaphoreSlim(1);
static int s_data;
[Benchmark]
public int Lock()
{
lock (s_lock)
{
s_data++;
return s_data;
}
}
[Benchmark]
public int SemaphoreSync()
{
try
{
s_semaphore.Wait();
s_data++;
return s_data;
}
finally
{
s_semaphore.Release();
}
}
[Benchmark]
public async Task<int> SemaphoreAsync()
{
try
{
await s_semaphore.WaitAsync().ConfigureAwait(false);
s_data++;
return s_data;
}
finally
{
s_semaphore.Release();
}
}

.NET 5

Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Lock 18.67 ns 0.108 ns 0.101 ns - - - -
SemaphoreSync 45.94 ns 0.162 ns 0.144 ns - - - -
SemaphoreAsync 72.93 ns 1.446 ns 1.608 ns 0.0086 - - 72 B

.NET 4.8

Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
Lock 17.26 ns 0.084 ns 0.070 ns - - - -
SemaphoreSync 115.19 ns 1.456 ns 1.290 ns - - - -
SemaphoreAsync 180.12 ns 1.705 ns 1.595 ns 0.0126 - - 80 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment