00-Java数组遍历性能对比

三种遍历方式性能对比

  1. 循环与数组的length比较
1
2
3
4
5
6
7
8
9
10
public class JavaMain {
static Object[] objs = new Object[10000000];
static int zero() {
int sum = 0;
for(int i = 0; i < objs.length; i++) {
sum ^= objs[i].hashCode();
}
return sum;
}
}
  1. 将数组length存在方法栈中
1
2
3
4
5
6
7
8
9
10
11
public class JavaMain {
static Object[] objs = new Object[10000000];
static int one() {
int sum = 0;
int len = objs.length;
for(int i = 0; i < len; i++) {
sum ^= objs[i].hashCode();
}
return sum;
}
}
  1. for-each循环
阅读更多