Home java Foreach vs Iterable.foreach in Java 8: Which is Better?

Foreach vs Iterable.foreach in Java 8: Which is Better?

Author

Date

Category

Which of the following is best practice in Java 8?

Java 8:

list.forEach (e - & gt; e.operation);

Java 7:

for (E e: list) {
  e.operation;
}

I have many loops that can be simplified with lambdas, but is there any real benefit to using Iterator.foreach ?

Will the performance and readability of the code improve?


Answer 1, authority 100%

From a performance standpoint, there are no promised discernible benefits of 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.

Ie it is clear that there will be no explicit parallelism. Adding concurrency would violate LSP.

On code readability: you probably only use Iterable.foreach with short one-line lambdas. If the “body” of the lambda grows, then readability is likely to be worse than in a loop.


Note: this answer works when using StreamAPI . If only java.util.Iterable is used then this answer stops working.

You will have a strong advantage when processing large amounts of data in parallel. If you want the loop to run in parallel, then you should use the following construction:

list.parallelStream (). forEach (e - & gt; e.operation);

However, using non-parallel streams when processing small amounts of data will take longer than foreach and loops.


Output:

  1. There is no performance difference between Iterable.foreach and the foreach loop.
  2. If the body of the lambda is small, then it is better to use Iterable.foreach .
  3. If you want a performance boost, then you better use parallelStream.foreach () .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions