c# - How to avoid slowdown due to locked code? -


i wondering how piece of locked code can slow down code though code never executed. here example below:

public void test_performanceunit() {     stopwatch sw = new stopwatch();     sw.start();     random r = new random();     (int = 0; < 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 machine. if remove lock block (but keep body), 750ms. double, though code never run!

of course code nothing. noticed while adding lazy initialization in class code checks if object initialized , if not initializes it. problem initialization locked , slows down after first call.

my questions are:

  1. why happening?
  2. how avoid slowdown

about why it's happening, has been discussed in comments : it's due initialization of try ... finally generated lock.


and avoid slowdown, can extract locking feature new method, locking mechanism initialized if method called.

i tried simple code :

public object testrand(random r) {     if (r.next(1) > 10)     {         return lockingfeature();     }     return r; }  private object lockingfeature() {     lock (_lock)     {         return null;     } } 

and here times (in ticks) :

your code, no lock   : ~500 code, lock : ~1200 code              : ~500 

edit : test code (running bit slower code no locks) on static methods, appears when code ran "inside" object, timings same. fixed timings according that.


Comments