我正在编写代码,我正在对数组值进行一些计算并将结果存储回数组。演示代码如下 -将值分配给数组索引并将值分配给变量在java中的性能差异
public class Test {
private int[] x = new int[100000000];
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Test t = new Test();
long start = System.nanoTime();
for(int i=0;i<100000000;i++) {
t.testing(i);
}
System.out.println("time = " + (System.nanoTime() - start)/1000);
}
public void testing(int a) throws Exception {
int b=1,c=0;
if(b<c || b < 1) {
throw new Exception("Invalid inputs");
}
int d= a>>b;
int e = a & 0x0f;
int f = x[d];
int g = x[e];
x[d] = f | g;
}
}
程序的主要逻辑在于
int d= a>>b;
int e = a & 0x0f;
x[d] = f | g;
当我测试此代码,花了110毫秒。 但不是assiging结果反馈给X [d],如果将它分配给一个变量作为
int h = f | g;
只用了3毫秒。
我想只将结果赋值给Array,但它大大地妨碍了性能。 这是一个时间关键的程序。
所以我想知道是否有任何替代数组在Java或任何其他方式,我可以避免这种妨碍?
我在默认的Sun JVM配置下测试了这段代码。
P.S.我尝试了不安全的API,但它没有帮助。
使用字典怎么样? – JoeC
你在什么环境下运行,我想知道?那样的结果对我来说似乎不太可能。在Java中测量性能需要您先“预热JVM”;我会三次运行测量并查看第三次穿过它们的数字。 – Gimby
@Gimby - 我也在热身后对它进行了测试,结果非常相似。 – Bull