java變量讀寫效率測試

主要測試全局變量、局部變量、volatile變量、原子變量的讀寫效率,源碼以下:oop

public class GloableVarientTest {
    private long temp = 0;測試

    public void test() {
        long loop = Integer.MAX_VALUE;
        long start = System.currentTimeMillis();
        for (long i = 0; i < loop; i++) {
            temp += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }atom

    public void testLocal() {
        long loop = Integer.MAX_VALUE;
        long temp = 0;
        long start = System.currentTimeMillis();
        for (long i = 0; i < loop; i++) {
            temp += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }源碼

    private volatile long volatileTemp = 0;class

    public void testVolatile() {
        long loop = Integer.MAX_VALUE;
        long start = System.currentTimeMillis();
        for (long i = 0; i < loop; i++) {
            volatileTemp += i;
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }test

    public void testAtomic() {
        AtomicLong atomicTemp = new AtomicLong(0);
        long loop = Integer.MAX_VALUE;
        long start = System.currentTimeMillis();
        for (long i = 0; i < loop; i++) {
            atomicTemp.addAndGet(i);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }效率

    public static void main(String[] args) {
        GloableVarientTest gv = new GloableVarientTest();
        gv.test();
        gv.testLocal();
        gv.testVolatile();
        gv.testAtomic();
    }
}變量

讀寫效率測試結果:局部變量  > 全局變量 >>> volatile變量 ≈ 原子變量im

相關文章
相關標籤/搜索