0

I have found that in Java using AtomicIntegers, GetAndDecrement is much slower than GetAndIncrement. Why does this happen?

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
Strin
  • 677
  • 9
  • 15

2 Answers2

1

Whichever one comes second is faster.

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

On my machine, this prints:

Time: 49264

Time: 4105

However, if we swap the order of the two operations:

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

Then we get:

Time: 43106

Time: 7697

Presumably the JVM or processor or something is doing some runtime optimizations.

Community
  • 1
  • 1
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
-1

They look pretty much the same to me --

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;
    }
}
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • Run it. When I ran it, the getAndDecrement() method took 5 times longer. Run and time it, don't post hypotheticals. – Anubian Noob Apr 17 '14 at 01:00
  • That's just the source code (admittedly a bit old). Would've been a comment but it wouldn't be legible that way. – Hot Licks Apr 17 '14 at 01:19
  • (It may be that newer implementations have moved the more popular increment to a native method, or some such.) – Hot Licks Apr 17 '14 at 01:21
  • This is the same as the newest implementation. – Anubian Noob Apr 17 '14 at 01:22
  • 1
    There's still a chance that increment is being overridden by a native implementation. The other, perhaps more likely possibility is that the JITC optimizes the increment but not the decrement, possibly because of the presence of native instructions to do the former. – Hot Licks Apr 17 '14 at 01:35