Home > development > What is the fastest lock in C#

What is the fastest lock in C#

August 26th, 2019

I often wonder what the fastest lock is in C#.

If course they all have their own pros and cons, but when it comes to raw speed, what is the fastest lock.

We have a couple of options, but the common ones are

  • Lock object
  • Semaphore
  • Mutex
  • Read writer lock
    • Read
    • Write

The test was to add 10 million random numbers and test the various locks.

As this is not a multi threaded application, the waiting for the lock is imaterial here, we are only testing getting the lock.

In other words, this is an ideal scenario, you are not waiting for any lock, you are simply getting it.

Raw lock test

Obviously not getting any locks is faster, followed by both the ReaderWriterLockSlim, (read lock and write lock), then the SemaphoreSlim and the Mutex was, by far, the worse of them all.

  • The ReaderWriterLockSlim is slower because extra work is spent looking for re-entry as well as using a SpinLock
  • The SemaphoreSlim is even slower because we do a SpinWait and wait other threads to release the lock, (or locks as we could have more than one).
  • The mutex class is slower still because it puts the thread to sleep until it has access to the handle, and then wakes it up again.

You have a look at the code on my github page.

Categories: development Tags: ,
Comments are closed.