0

Consider Below 2 examples.

1 With Streams

myList.stream().map(this::getInt).max(Integer::compareTo);

2 Old way

int max = Integer.MIN_VALUE;
for (MyItem item : myList) {
    max = Math.max(max, getInt(item));    
}

Above getInt method accepts a MyItem argument and returns an int result.

Here, #2 gives me a much lower latency compared to #1. Does anyone have an idea why or anything going wrong for me?

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
  • 4
    A claimed performance difference without documenting the measuring method is worthless. See [How do I write a correct micro-benchmark in Java?](https://stackoverflow.com/q/504103/2711488), I bet, you violated one rule or two. A helpful pointer might be the [Java lambdas 20 times slower than anonymous classes](https://stackoverflow.com/q/34585444/2711488) Q&A. – Holger May 06 '20 at 08:30
  • @Holger Are you suggesting me to put values with the method? – Supun Wijerathne May 07 '20 at 08:30
  • 1
    No, I’m suggesting to document how you came to the conclusion that your second code has “much lower latency” than the first. If we used measuring code instead of feelings, post that code. Then, we can tell you what you made wrong. Or you follow the already posted links and find out yourself. – Holger May 07 '20 at 10:25

2 Answers2

3
myList.stream().mapToInt(this::getInt).max()

Try mapping to an IntStream. An IntStream works with ints internally, which avoids the overhead of boxing and unboxing Integer objects. Also, IntStream.max() doesn't need a custom comparator.

So you suggest that the prominent reason is 'boxing' and 'unboxing'?

Without running it through your benchmark I don't know if it'll match the for loop's performance. But it'll be an improvement. If it's not good enough then I suggest sticking with the loop as I don't see any other way to improve it.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

You should probably take advantage of features of Streams, that should optimise these cases. Read the docs for Streams, the first example shows the optimised path for IntStream.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

     int max = myList.stream()
                      .mapToInt(this::getInt)
                      .max()
                      .orElse(Integer.MIN_VALUE);
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69