I\'m doing a very silly benchmark on the ReaderWriterLock with this code, where reading happens 4x more often than writting:
class Program
{
static void
Edit 2: Simply removing the Thread.Sleep
calls from ReadThread
and WriteThread
, I saw Locked
outperform RWLocked
. I believe Hans hit the nail on the head here; your methods are too fast and create no contention. When I added Thread.Sleep(1)
to the Get
and Add
methods of Locked
and RWLocked
(and used 4 read threads against 1 write thread), RWLocked
beat the pants off of Locked
.
Edit: OK, if I were actually thinking when I first posted this answer, I would've realized at least why you put the Thread.Sleep
calls in there: you were trying to reproduce the scenario of reads happening more frequently than writes. This is just not the right way to do that. Instead, I would introduce extra overhead to your Add
and Get
methods to create a greater chance of contention (as Hans suggested), create more read threads than write threads (to ensure more frequent reads than writes), and remove the Thread.Sleep
calls from ReadThread
and WriteThread
(which actually reduce contention, achieving the opposite of what you want).
I like what you've done so far. But here are a few issues I see right off the bat:
Thread.Sleep
calls? These are just inflating your execution times by a constant amount, which is going to artificially make performance results converge.Thread
objects in the code that's measured by your Stopwatch
. That is not a trivial object to create.Whether you will see a significant difference once you address the two issues above, I don't know. But I believe they should be addressed before the discussion continues.