Alex Rivera | Logout

Performance of Interlocked.Increment

Asked 2009-06-23T17:46:46.267
23

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

Edit
Report

2 Answers

7

Think about it for a moment, and you'll realize an Increment call cannot be any faster than a simple application of the increment operator. If it were, then the compiler's implementation of the increment operator would call Increment internally, and they'd perform the same.

But, as you can see by testing it for yourself, they don't perform the same.

The two options have different purposes. Use the increment operator generally. Use Increment when you need the operation to be atomic and you're sure all other users of that variable are also using interlocked operations. (If they're not all cooperating, then it doesn't really help.)

answered 2009-06-23T17:53:30.220
2

My perfomance test:

volatile: 65,174,400

lock: 62,428,600

interlocked: 113,248,900

TimeSpan span = TimeSpan.FromSeconds(5);

object syncRoot = new object();
long test = long.MinValue;

Do(span, "volatile", () => {

    long r = Thread.VolatileRead(ref test);

    r++;

    Thread.VolatileWrite(ref test, r);
});

Do(span, "lock", () =>
{
    lock (syncRoot)
    {
        test++;
    }
});

Do(span, "interlocked", () =>
{
    Interlocked.Increment(ref test);
});
answered 2012-04-13T13:18:48.547

Your Answer