A foreach loop versus an Iterable loop.foreach in Java 8: what's better?
Which of the following is the best practice in Java 8?
Java 8:
list.forEach(e -> e.operation);
Java 7:
for (E e : list) {
e.operation;
}
I have a lot of loops that can be simplified with lambdas, but are there any real benefits from using Iterator.foreach
?
Will the performance and readability of the code improve?
1 answers
In terms of performance, there are no promised noticeable benefits from using Iterable.forEach
over foreach
.
According to the official javadoc on Iterable.forEach
:
Performs the given action on the contents of the Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.
I.e. it is clear that there will be no explicit parallelism. Addendum concurrency would be a violation of LSP.
About code readability: you probably only use Iterable.foreach
with short, single-line lambdas. If the" body " of the lambda increases, the readability is likely to be worse than in the loop.
Note: this answer works when using StreamAPI
. If only java.util.Iterable
is used, this response stops working.
You will have a strong advantage when processing large amounts of data in parallel. If you if you want the loop to run in parallel, you should use this construction:
list.parallelStream().forEach(e -> e.operation);
However, using non-parallel streams when processing a small amount of data will take longer than foreach
and cycles.
Conclusion:
- There is no difference in performance between
Iterable.foreach
and theforeach
loop. - If the lambda body is small, it is better to use
Iterable.foreach
. - If you want a performance boost, then you better use
parallelStream.foreach()
.