在看GO语言时看到别人写了一段把数组先获取长度用变量保存长度,在去循环遍历的代码。
以前写的都是在for循环里面条件判断时在获取长度,想想这样性能能提高多少,就用java测试下下面是代码
package test;
public class Test1 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
long sum1 = 0, sum2 = 0;
//测试1万次
for(int a=0; a<10000; ++a){
long time1 = System.nanoTime();
for(int j=0; j<10000; ++j){
for(int i=0; i<arr.length; ++i){
int t = arr[i];
}
}
//计算处理完任务的纳秒
time1 = System.nanoTime() - time1;
sum1 += time1;
long time2 = System.nanoTime();
for(int j=0; j<10000; ++j){
int len = arr.length;
for(int i=0; i<len; ++i){
int t = arr[i];
}
}
//计算处理完任务的纳秒
time2 = System.nanoTime() - time2;
sum2 += time2;
}
System.out.println("sum1:"+sum1+", sum2:"+sum2+",sum1/sum2:"+(sum1*1.00)/sum2);
}
}
结果:
1.sum1:1834534466, sum2:342085548,sum1/sum2:5.3627944142206205
2.sum1:1854752830, sum2:345797811,sum1/sum2:5.363691645809753
3.sum1:1855739585, sum2:346774010,sum1/sum2:5.351437914854115
4.sum1:1855739585, sum2:346774010,sum1/sum2:5.351437914854115
5.sum1:1850499523, sum2:345726700,sum1/sum2:5.352492367526141