I was playing with Disruptor framework and its port for .NET platform and found an interesting case. May be I completely miss something so I'm looking for help from almighty Community.
long iterations = 500*1000*1000;
long testValue = 1;
//.NET 4.0. Release build. Mean time - 26 secs;
object lockObject = new object();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
lock (lockObject)
{
testValue++;
}
}
sw.Stop();
//Java 6.25. Default JVM params. Mean time - 17 secs.
Object lock = new Object();
long start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
synchronized (lock)
{
testValue++;
}
}
long stop = System.currentTimeMillis();
It seems that acquiring the lock in the scenario with a signle thread in .NET costs just 50% more than in Java. At first I was suspicious at timers but I've ran the same test for a few times with results just around mentioned above mean values. Then I was suspicious at synchronized block of code but it does no more than just monitorenter / monitorexit byte code instructions - the same thing as lock keyword in .NET. Any other ideas why taking a lock is so expensive in .NET vs Java?
Interlocked.Increment(ref testValue)
instead of locking, or lock it once just for the duration of the entire loop. The performance differences you are seeing shouldn't be evident if you use a proper locking pattern. – ChapellInterlocked.Increment
would take longer, which just defies and answer to the question. – FullbodiedInterlocked.Increment
instead of locking (assuming the lock is inside the loop) is about 60% faster for me. My point being that all this code is doing is atomically incrementing a long. There are better ways to do that instead of using a full-blown lock, like Interlocked. – ChapellInterlocked.Increment
on this machine;lock
results are similar to the OPs, whileReaderWriterLockSlim.EnterWriteLock
comes just ahead of theInterlocked
results. – Fullbodied