I have read another SO question: When is ReaderWriterLockSlim better than a simple lock?
And it does not explain exactly why ReaderWriterLockSlim
so slow compared to lock
.
My test is yes - testing with zero contention but still it doesnt explain the staggering difference.
Read lock takes 2.7s, Write lock 2.2s, lock 1.0s
This is complete code:
using System;
using System.Diagnostics;
using System.Threading;
namespace test
{
internal class Program
{
static int[] data = new int[100000000];
static object lock1 = new object();
static ReaderWriterLockSlim lock2 = new ReaderWriterLockSlim();
static void Main(string[] args)
{
for (int z = 0; z < 3; z++)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < data.Length; i++)
{
lock (lock1)
{
data[i] = i;
}
}
sw.Stop();
Console.WriteLine("Lock: {0}", sw.Elapsed);
sw.Restart();
for (int i = 0; i < data.Length; i++)
{
try
{
lock2.EnterReadLock();
data[i] = i;
}
finally
{
lock2.ExitReadLock();
}
}
sw.Stop();
Console.WriteLine("Read: {0}", sw.Elapsed);
sw.Restart();
for (int i = 0; i < data.Length; i++)
{
try
{
lock2.EnterWriteLock();
data[i] = i;
}
finally
{
lock2.ExitWriteLock();
}
}
sw.Stop();
Console.WriteLine("Write: {0}\n", sw.Elapsed);
}
Console.ReadKey(false);
}
}
}