关于for循环和foreach循环,使用java的童鞋已经熟悉得不能在熟悉了,那么关于他们的区别,咱们知道多少呢?java
for循环是基础语法,全部不在赘述数组
foreach循环也叫加强型的for循环,是JDK5.0的新特性,foreach循环的加入简化了集合的遍历,缺点是丢掉了索引信息bash
foreach循环语法性能
for(type element: array){
}
复制代码
for循环与foreach循环性能比较ui
ArrayList<Integer> arrayList = new ArrayList<>();
LinkedList<Integer> linkedList = new LinkedList<>();
for (int i = 0; i < 100000; i++) {
arrayList.add(i);
linkedList.add(i);
}
int number;
long start = System.currentTimeMillis();
for (int i = 0; i < arrayList.size(); i++) {
number = arrayList.get(i);
}
long end = System.currentTimeMillis();
long result = end - start;
System.out.println("ArrayList for循环消耗时间:" + result);
start = System.currentTimeMillis();
for (int i : arrayList) {
number = i;
}
end = System.currentTimeMillis();
result = end - start;
System.out.println("ArrayList foreach循环消耗时间:" + result);
start = System.currentTimeMillis();
for (int i = 0; i < linkedList.size(); i++) {
number = linkedList.get(i);
}
end = System.currentTimeMillis();
result = end - start;
System.out.println("LinkList for循环消耗时间:" + result);
start = System.currentTimeMillis();
for (int i : linkedList) {
number = i;
}
end = System.currentTimeMillis();
result = end - start;
System.out.println("LinkList foreach循环消耗时间:" + result);
复制代码
运行结果spa
ArrayList for循环消耗时间:8
ArrayList foreach循环消耗时间:12
LinkList for循环消耗时间:7779
LinkList foreach循环消耗时间:3
复制代码
能够看出,ArrayList中for循环比foreach循环稍快一点,而在LinkList中,foreach循环比for循环快不少code
循环次数增长,ArrayList中for循环仍然比foreach循环快,而LinkList中for循环可能会被程序卡死索引
总结:element