java – What is the difference between Collection.stream (). ForEach () and Collection.forEach ()?

This answer concerns itself with the performance of the various loop implementations. It is only marginally relevant for loops that are called VERY OFTEN (like millions of calls). In most cases the contents of the loop will be by far the most expensive item. For situations where you cycle very often, this may still be of interest.

You should repeat this test with the target system as this is implementation specific, ( full source code ).

I run openjdk version 1.8.0_111 on a fast Linux machine.

I wrote a test that loops 10 ^ 6 times on a list using this various sized code for integers (10 ^ 0 -> 10 ^ 5 entries).

The results are below, the fastest method varies depending on the amount of entries in the list.

However, in the worst situations, the loop on 10 ^ 5 voices 10 ^ 6 times took 100 seconds for the worst performer, so other considerations are more important in almost all situations.

public int outside = 0;

private void forCounter(List<Integer> integers) {
    for(int ii = 0; ii < integers.size(); ii++) {
        Integer next = integers.get(ii);
        outside = next*next;
    }
}

private void forEach(List<Integer> integers) {
    for(Integer next : integers) {
        outside = next * next;
    }
}

private void iteratorForEach(List<Integer> integers) {
    integers.forEach((ii) -> {
        outside = ii*ii;
    });
}
private void iteratorStream(List<Integer> integers) {
    integers.stream().forEach((ii) -> {
        outside = ii*ii;
    });
}

Here are my times: milliseconds / function / number of entries in the list. Each run is 10 ^ 6 cycles.

                           1    10    100    1000    10000
         for with index   39   112    920    8577    89212
       iterator.forEach   27   116    959    8832    88958
               for:each   53   171   1262   11164   111005
iterable.stream.forEach  255   324   1030    8519    88419

If you repeat the experiment, I posted the full source code . Please edit this answer and add results with a tested system notation.

I got:
                                  1    10    100    1000    10000
              iterator.forEach   27   106   1047    8516    88044
                      for:each   46   143   1182   10548   101925
       iterable.stream.forEach  393   397   1108    8908    88361
                for with index   49   145    887    7614    81130

(MacBook Pro, Intel Core i7 2.5GHz, 16GB, macOS 10.12.6)

Leave a comment