I am wondering how a piece of locked code can slow down my code even though the code is never executed. Here is an example below:
public void Test_PerformanceUnit()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Random r = new Random();
for (int i = 0; i < 10000; i++)
{
testRand(r);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
public object testRand(Random r)
{
if (r.Next(1) > 10)
{
lock(this) {
return null;
}
}
return r;
}
This code runs in ~1300ms on my machine. If we remove the lock block (but keep its body), we get 750ms. Almost the double, even though the code is never run!
Of course this code does nothing. I noticed it while adding some lazy initialization in a class where the code checks if the object is initialized and if not initializes it. The problem is that the initialization is locked and slows down everything even after the first call.
My questions are:
- Why is this happening?
- How to avoid the slowdown
lock
intensively - I wouldn't really worry about it.sw.ElapseMilliseconds
.) This "slowdown" (of ~0.00006s) is likely due to the fact thatlock
includes atry/finally
block which is probably being setup when the method is called. Try putting the contents oftestRand
in the loop itself; you'll see almost no slowdown at that point.try{}finally{}
statement. If you use it (even empty, with no embedded code) the same slowdown occurs. Alock
statement implements atry{}finally{}
.