I had this piece of code below:
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> arg0, Map.Entry<Integer, Integer> arg1) {
return arg1.getValue().compareTo(arg0.getValue());
}
});
Than IntelliJ IDEA friendly suggested that I can replace the code above to a lambda expression like below:
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), (arg0, arg1) -> {
return arg1.getValue().compareTo(arg0.getValue());
});
Well guess what happened, in my method the execution time of the 2. code executed 20 times slower?! First version took 7 miliseconds to sort the list, and after lambda expression it was 140 miliseconds?!
Am I missing something here? I didn't test if the execuation time proportionally increases as data grows. maybe thats just the initial one time cpu time?
The first time a lambda is used, the JVM has to generate the byte code of the class and load it. The first time any lambda is used, most of the lambda code generating library is loaded.
I have found that using a Lambda Comparator can be slower. It is likely that in future version this will not be the case. More importantly, lambda code definitely needs to be loaded and warmed up to be fast.
Your code isn't run long enough to say. I would warm the code up for at least 2 - 10 seconds before taking any measurement.
When you use a Comparator to sort a large list it can be called
N log2 N
times which is a lot. Any inefficiency with show up as significant.