Java 8 Iterable.forEach() vs foreach loop

前端 未结 8 1306
暗喜
暗喜 2020-11-22 14:36

Which of the following is better practice in Java 8?

Java 8:

joins.forEach(join -> mIrc.join(mSession, join));

Java 7:



        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 15:06

    TL;DR: List.stream().forEach() was the fastest.

    I felt I should add my results from benchmarking iteration. I took a very simple approach (no benchmarking frameworks) and benchmarked 5 different methods:

    1. classic for
    2. classic foreach
    3. List.forEach()
    4. List.stream().forEach()
    5. List.parallelStream().forEach

    the testing procedure and parameters

    private List list;
    private final int size = 1_000_000;
    
    public MyClass(){
        list = new ArrayList<>();
        Random rand = new Random();
        for (int i = 0; i < size; ++i) {
            list.add(rand.nextInt(size * 50));
        }    
    }
    private void doIt(Integer i) {
        i *= 2; //so it won't get JITed out
    }
    

    The list in this class shall be iterated over and have some doIt(Integer i) applied to all it's members, each time via a different method. in the Main class I run the tested method three times to warm up the JVM. I then run the test method 1000 times summing the time it takes for each iteration method (using System.nanoTime()). After that's done i divide that sum by 1000 and that's the result, average time. example:

    myClass.fored();
    myClass.fored();
    myClass.fored();
    for (int i = 0; i < reps; ++i) {
        begin = System.nanoTime();
        myClass.fored();
        end = System.nanoTime();
        nanoSum += end - begin;
    }
    System.out.println(nanoSum / reps);
    

    I ran this on a i5 4 core CPU, with java version 1.8.0_05

    classic for

    for(int i = 0, l = list.size(); i < l; ++i) {
        doIt(list.get(i));
    }
    

    execution time: 4.21 ms

    classic foreach

    for(Integer i : list) {
        doIt(i);
    }
    

    execution time: 5.95 ms

    List.forEach()

    list.forEach((i) -> doIt(i));
    

    execution time: 3.11 ms

    List.stream().forEach()

    list.stream().forEach((i) -> doIt(i));
    

    execution time: 2.79 ms

    List.parallelStream().forEach

    list.parallelStream().forEach((i) -> doIt(i));
    

    execution time: 3.6 ms

提交回复
热议问题