我发现在使用AtomicIntegers
的Java中,GetAndDecrement
比GetAndIncrement
慢得多。为什么会这样?
答案 0 :(得分:1)
无论哪一个来得快,都会更快。
AtomicInteger a = new AtomicInteger(1);
long start1 = System.nanoTime();
a.decrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start1));
AtomicInteger b = new AtomicInteger(1);
long start2 = System.nanoTime();
a.incrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start2));
在我的机器上打印:
时间:49264
时间:4105
但是,如果我们交换两个操作的顺序:
AtomicInteger a = new AtomicInteger(1);
long start1 = System.nanoTime();
a.incrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start1));
AtomicInteger b = new AtomicInteger(1);
long start2 = System.nanoTime();
a.decrementAndGet();
System.out.println("Time: " + (System.nanoTime()-start2));
然后我们得到:
时间:43106
时间:7697
据推测,JVM或处理器正在进行一些运行时优化。
答案 1 :(得分:-1)
他们对我看起来几乎一样 -
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final int getAndDecrement() {
for (;;) {
int current = get();
int next = current - 1;
if (compareAndSet(current, next))
return current;
}
}