I have quickly read over the Oracle Lambda Expression documentation.
This kind of example has helped me to understand better, though:
//Old way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
System.out.println(n);
}
//New way:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));
//or we can use :: double colon operator in Java 8
list.forEach(System.out::println);
Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method? Which would be better option in terms of performance. Lambda or simple loop.
My advice would be:
Use the style that you and your coworkers agree is most maintainable.
If you and your colleagues are not yet comfortable with lambdas, keep learning.
Don't obsess over performance. It is often not the most important thing.
Generally speaking, lambdas and streams provide a more concise and (once everyone is up to speed) more readable way of expressing this kind of algorithm. Improved performance is not their primary goal.
If performance does become an issue, then the standard advice is to code, test, benchmark, profile and optimize. And do it in that order! You can easily waste a lot time by optimizing at the coding stage, or by optimizing code that has minimal impact on overall application performance.
In this specific example, the performance difference is going to be too small to measure. And if you scaled up to a list of millions of elements, the performance will be dominated by the time taken to build the list and write the numbers. The different ways of iteration will only contribute a small part to the overall performance.
And for folks, who (despite all of the above) still want to know whether it is faster to use a lambda or a conventional loop, the best general answer is:
- A conventional loop is unlikely to be slower, under most circumstances.
- It depends on all sorts of contextual factors that are difficult to analyze.
- Performance characteristics are liable to change as Java compiler technology evolves.
We could give you an answer for a specific example with a specific Java major/minor/patch release, but it would be unwise to generalize.