性能循环与整数与长索引 [英] Performance loop with integer vs Long index
问题描述
有什么想法吗?
$ b我想知道为什么需要更长的时间来运行一个长索引与整数索引的循环?$ b
谢谢
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);
可能与单词大小有关您的JVM使用。对于32位的字长, ints
将需要一个字,而 longs
需要2个字来存储。所以基本上读取 long
的值基本上是2次读取,而写入它们又是2次写入。
long
类型增量有任何指令集。它有 iinc
,但没有 linc
。因此,增量操作也必须经过 iinc
(可能再次使用2个字,可能也会导致2 iinc
操作)。总之,与 int
类型相比, long
类型的算术有些复杂。但当然不应该太担心。我猜这些可能是造成速度缓慢的原因。 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");
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.
这篇关于性能循环与整数与长索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!