AtomicInteger implementation and code duplication

后端 未结 5 851
眼角桃花
眼角桃花 2021-02-12 17:00

Warning: the question is a little long, but the part below the separation line is for curiosity only.

Oracle\'s JDK 7 implementation of AtomicInteger includes t

5条回答
  •  情书的邮戳
    2021-02-12 17:09

    I'll give new supposition. If we look into byte code of AtomicInteger we will see, that the main difference between them is that addAndGet uses iload_ instruction, and incrementAndGet uses iconst_ instruction:

    public final int addAndGet(int);
       ...
       4:   istore_2
       5:   iload_2
       6:   iload_1
       7:   iadd
    
    public final int incrementAndGet();
       ...
       4:   istore_1
       5:   iload_1
       6:   iconst_1
       7:   iadd
    

    It seems, that iconst_+iadd translates as INC instruction, due to iload_...iadd as ADD instruction. This all relates to commonly known question about ADD 1 vs INC and so on:

    Relative performance of x86 inc vs. add instruction

    Is ADD 1 really faster than INC ? x86

    This could be the answer, why addAndGet is slightly faster than incrementAndGet

提交回复
热议问题