When is ReaderWriterLockSlim better than a simple lock?
Solution 1:
In your example, the sleeps mean that generally there is no contention. An uncontended lock is very fast. For this to matter, you would need a contended lock; if there are writes in that contention, they should be about the same (lock
may even be quicker) - but if it is mostly reads (with a write contention rarely), I would expect the ReaderWriterLockSlim
lock to out-perform the lock
.
Personally, I prefer another strategy here, using reference-swapping - so reads can always read without ever checking / locking / etc. Writes make their change to a cloned copy, then use Interlocked.CompareExchange
to swap the reference (re-applying their change if another thread mutated the reference in the interim).
Solution 2:
My own tests indicate that ReaderWriterLockSlim
has about 5x the overhead as compared to a normal lock
. That means for the RWLS to outperform a plain old lock the following conditions would generally be occurring.
- The number of readers significantly outnumbers the writers.
- The lock would have to be held long enough to overcome the additional overhead.
In most real applications these two conditions are not enough to overcome that additional overhead. In your code specifically, the locks are held for such a short period of time that the lock overhead will probably be the dominating factor. If you were to move those Thread.Sleep
calls inside the lock then you would probably get a different result.