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?
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
Try mapping to an
IntStream
. AnIntStream
works withint
s internally, which avoids the overhead of boxing and unboxingInteger
objects. Also,IntStream.max()
doesn't need a custom comparator.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.