1. 程式人生 > >[Java] Java For Each 迴圈效率分析

[Java] Java For Each 迴圈效率分析

目錄

Java For Each 迴圈效率分析

迴圈方式

  • for i

  • for each

  • while (iterator.hasNext()) {} / for( Iterator 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

  1. Java8 Lambda表示式和流操作如何讓你的程式碼變慢5倍

更多

image

掃碼關注或搜尋架構探險之道獲取最新文章,不積跬步無以至千里,堅持每週一更,堅持技術分享。我和你們一起成長 ^_^