Performance loop with integer vs Long index

时光总嘲笑我的痴心妄想 提交于 2020-01-16 04:13:47

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/29332464/performance-loop-with-integer-vs-long-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!