0

I made some PoCs to compare the performance of two types of implementation interacting list.

The fist one was using pure java using foreach and checking with 'if' each element.

The second approach was using lambda like this:

int max1 =  lists1.stream()
                  .mapToInt(i -> i)
                  .max()
                  .getAsInt();

long finalCount = lists1.stream()
                        .filter(p -> p.intValue() == max1)
                        .count();

Obviously using lambda was 5 time faster than using classic java foreach.

I'm feeling very confidence to make mandatory to use a lambda in my team in my current project like a rule, forbidding the use of classic java foreach.

My questions is if exist some scenario that I cannot apply this rule (lambda required), I mean, if exist exception where I cannot use lambda working with Collections.

GhostCat
  • 137,827
  • 25
  • 176
  • 248

2 Answers2

6

Lambda+streams obviously faster? Not so.

It greatly depends on the situation, but in general, Java 7 loops are faster than streams, because there's less going on.

To answer your question: "No"; you should not mandate that lambdas should always be used, because:

  • it's a style thing; both forms are acceptable
  • some loops turn into train wrecks when implemented as streams
  • your reasons are baseless
  • readability almost always beats "performance"

For parallel streams, processing can be faster, but only if the stream is large enough to justify the overheads of managing the stream. As a rule of thumb, if you've got at least 1000 elements to process, try a stream.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

The absolute first thing - benchmarking Java code is complicated. Meaning: unless you did already follow the rules outlined in that prior link chances are high that your measurements are bogus.

Beyond that: it is true that lambdas make use of the invokedynamic bytecode instruction, which can in turn lead to improved performance.

But this does in no way support to force such a policy for a whole team.

The real answer is: educate your team about the pros and cons of streams and lambdas. Enable them to make an informed decision when and how to make use of these concepts. Ensure that people understand what they are doing, instead of giving them a checklist with orders to follow.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248