1

I presume this atomic operation is faster than ++. I only see advantages favoring Interlocked.Increment. What are its disavantages?

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

2 Answers2

11

Atomic means it is thread-safe (i.e. it is impossible for one thread to read the value while another is changing it.) Which makes it slower, not faster, due to the need to use thread synchronization mechanisms. You want to use ++ if you don't care about thread-safety. Here is some discussion on the relative performance of the ++ operator in different contexts.

Community
  • 1
  • 1
jlew
  • 10,491
  • 1
  • 35
  • 58
  • I just tested it, 1e8 times `++` is roughly a second, the same number of `Interlocked.Increment` operations uses more than double this time on my PC. – Jader Dias May 23 '11 at 13:51
  • Exactly. Your results agree with the theory. – jlew May 23 '11 at 13:55
1

Atomic does not mean it is faster. In fact, it will almost definitely be slower.

In concurrent programming, an operation (or set of operations) is atomic, linearizable, indivisible or uninterruptible if it appears to the rest of the system to occur instantaneously.

This merely means there are no observable side effects during the operation. It does not say anything about how long the operation takes.

Thorarin
  • 47,289
  • 11
  • 75
  • 111