Performance of Interlocked.Increment

后端 未结 6 1987
陌清茗
陌清茗 2020-12-15 18:30

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

6条回答
  •  孤城傲影
    2020-12-15 19:06

    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);
    });
    

提交回复
热议问题