Java For Each 循环效率分析
循环方式
-
for i
-
for each
-
while (iterator.hasNext()) {} / for( Iterator<Student> iterator = students.iterator();iterator.hasNext;){}
-
students.forEach(p -> {...});
循环效率分析
测试代码
@Test
public void lamadaForEachTest() {
List<Student> students = new ArrayList<>();
List<Long> stat = new ArrayList<>();
int max = Integer.MIN_VALUE;
//添加数据
for (int i = 0; i < 100000; i++) {
students.add(new Student("s" + i, i));
}
System.out.println("start for i");
long t = System.currentTimeMillis();
//传统索引循环
for (int i = 0; i < students.size(); i++) {
max = Integer.max(max, students.get(i).getAge());
}
stat.add(System.currentTimeMillis() - t);
System.out.println();
System.out.println("end for i");
System.out.println("start for each");
t = System.currentTimeMillis();
//for each 循环
for (Student s : students) {
max = Integer.max(max, s.getAge());
}
stat.add(System.currentTimeMillis() - t);
System.out.println("end for each");
System.out.println("start for iterator");
t = System.currentTimeMillis();
//迭代器循环
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
max = Integer.max(max, iterator.next().getAge());
}
stat.add(System.currentTimeMillis() - t);
System.out.println("start for lamda");
t = System.currentTimeMillis();
int max1 = Integer.MIN_VALUE;
//JDK8 forEach循环
students.forEach(p -> {
Integer.max(max1, p.getAge());
});
stat.add(System.currentTimeMillis() - t);
System.out.println();
System.out.println(stat);
//1w-100w 数量级,前三种循环速度更快
//1000W 数量级,四种方法循环速度差不多
}
@Data
@ToString
@Accessors(chain = true)
@AllArgsConstructor
class Student {
private String name;
private Integer age;
}
数据级(10^1) | 循环耗时 |
---|---|
1 | [0, 0, 0, 79] |
2 | [0, 0, 0, 84] |
3 | [1, 0, 0, 63] |
4 | [2, 1, 1, 57] |
5 | [3, 29, 7, 53] |
6 | [15, 17, 17, 58] |
7 | [96, 93, 97, 137] |
8 | java.lang.OutOfMemoryError: GC overhead limit exceeded (PC-8G) |
REFRENCES
更多

扫码关注或搜索架构探险之道
获取最新文章,不积跬步无以至千里,坚持每周一更,坚持技术分享。我和你们一起成长 _ !
网友评论