Home > Mobile >  Why lock is 240% faster than ReaderWriterLockSlim?
Why lock is 240% faster than ReaderWriterLockSlim?

Time:06-03

I have read another SO question: SPST/DPDT electric switches

The device at the left is used to control a single electric lamp from a single location. The device at the right is used to control two lamps from two different locations.¹ The device at the left is cheaper to buy, it requires less wiring, it is simpler to install and operate, and it loses less energy due to heat than the device at the right.

The analogy with the SPST/DPDT electric switches is probably far from perfect, but my point is that a lock is comparatively a simpler mechanism than the ReaderWriterLockSlim. It is used to enforce a single policy to a homogenous group of worker threads. On the other hand a ReaderWriterLockSlim is used to enforce two different policies to two separate groups of workers (readers and writers), regarding to how they interact with members of the same group and the other group. It should be of no big surprise that the more complex mechanism has a higher operational cost (overhead) than the simpler mechanism. That's the cost that you have to pay in order to get finer control of the worker threads.

¹ Or maybe not. I am not an electrician!

CodePudding user response:

Thanks to @canton and @KevinGosse - I found my 2013 question perfectly answered by @HansPassant: When exactly does .NET Monitor go to kernel-mode?

So lock is faster in no-contention scenario simply because it has lighter logic and kernel mode is not involved.

  • Related