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

- 88,211
- 155
- 421
- 625
-
7Why do you think it is faster than `++`? – Lasse V. Karlsen May 23 '11 at 13:42
-
2You do no single threaded programming? – Anthony Pegram May 23 '11 at 13:42
-
This has already been answered here: http://stackoverflow.com/questions/1034070/performance-of-interlocked-increment – Niki May 23 '11 at 13:44
-
@Lasse because I supposed it was executed in a single CPU cycle, or equivalent. – Jader Dias May 23 '11 at 17:58
2 Answers
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.
-
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
-
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.

- 47,289
- 11
- 75
- 111