1

I am wondering why it takes so much longer to run a loop with a long index vs. an integer index?

Any idea?

Thanks

int n = 1000_000_000;
long n2 =n;
long t1 = System.currentTimeMillis();
for( int idx = 0; idx<n;idx++){

}
long t2 = System.currentTimeMillis();
for( long idx = 0; idx<n2;idx++){

}
long t3 = System.currentTimeMillis();
long dt1 = t2-t1;
long dt2 = t3-t2;
System.out.println("with int = took " + dt1 +"ms");
System.out.println("with long = took " + dt2 +"ms");
6
  • I forgot the output: with int = took 3ms with long = took 337ms Commented Mar 29, 2015 at 17:37
  • 2
    How do I write a correct micro-benchmark in Java? Commented Mar 29, 2015 at 17:38
  • Are you saying something is not correct? Commented Mar 29, 2015 at 17:45
  • 1
    Such loops could be optimized by the hotspot compiler (especially with many iterations), since they have no sideeffects. Commented Mar 29, 2015 at 17:52
  • What baffles me is: the JIT really doesn't optimize away these empty loops?! Commented Mar 29, 2015 at 18:04

2 Answers 2

2

It possible has something to do with the word size that your JVM uses. For a 32 bit word size, ints will require one word, whereas longs would require 2 words for storage. So basically reading long value is basically 2 reads, and writing them is again 2 writes.

Another thing is increment operation. JVM spec doesn't have any instruction set for long type increment. It has iinc, but don't have linc. So, the increment operation also has to go through iinc (that might again use 2 words, possible it can also result in 2 iinc operations). In all, arithmetics on long type are a little bit complicated as compared to that on int type. But certainly should not be of too much concerns. I guess these are possible reasons for slight slow result.

Sign up to request clarification or add additional context in comments.

Comments

0

Java's optimizer (Oracle JDK 1.8.0_60) is able to elide the int-loop, but it does not know how to optimize out the long-loop.

Changing n from 1000_000_000 to 2000_000_000 has no effect on the run time of the int-loop, but it causes the long-loop to run twice as long.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.