I had a counter behind a lock that a profiler kept flagging, and I couldn't figure out why. The lock was basically never contended. One thread wrote to it almost all the time; the lock was there for the rare second writer that might show up. So I expected it to cost close to nothing. It didn't cost nothing. It cost about 24 nanoseconds every single acquire, and on a hot path that adds up to a line you can see in a flame graph.
The thing I'd stopped thinking about is what lock (someObject) actually compiles to. It's Monitor.Enter and Monitor.Exit wrapped in a try/finally, and Monitor hangs its state off the object's sync block. Even with no contention at all, you pay for that bookkeeping on every acquire and release. For years that was just the price of the lock keyword and there was nothing to do about it.
Since .NET 9 there is. There's a real type now, System.Threading.Lock , and the compiler special-cases it: if you lock on a variable whose type is Lock , it doesn't go through Monitor at all.…