Search code examples
.netperformanceinterlockedinterlocked-increment

Performance of Interlocked.Increment


Is Interlocked.Increment(ref x) faster or slower than x++ for ints and longs on various platforms?


Solution

  • It is slower since it forces the action to occur atomically and it acts as a memory barrier, eliminating the processor's ability to re-order memory accesses around the instruction.

    You should be using Interlocked.Increment when you want the action to be atomic on state that can be shared between threads - it's not intended to be a full replacement for x++.