java变量读写效率测试

主要测试全局变量、局部变量、volatile变量、原子变量的读写效率,源码如下:

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

    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;

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

    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变量 ≈ 原子变量

猜你喜欢

转载自my.oschina.net/u/1268334/blog/2254540