Stopwatch on Interlocked.Increment(ref x) vs. lock (y) { x++; }
Given 10 million iterations:
object y = new object();
const int iterations = 10000000;
Which is faster, InterlockedIncrement:
stopWatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
Interlocked.Increment(ref x);
}
stopWatch.Stop();
Console.WriteLine("Interlocked took " + stopWatch.ElapsedMilliseconds);
Or lock:
stopWatch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
lock (y)
{
x++;
}
}
stopWatch.Stop();
Console.WriteLine("lock took " + stopWatch.ElapsedMilliseconds);
The answer surprised me:
Interlocked took 168
lock took 389
Best,
Brian