主要测试全局变量、局部变量、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