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");
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
EKK
  • 171
  • 2
  • 12

2 Answers2

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
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.