0

EDIT: This is actually a question on leetcode. So the benchmarking is performed by leetcode.

Somewhere in my program, I have to sort a list of Map.Entry<Character, Integer>. Originally, I used the traditional way to override the Comparator for the sort. Then, I also tried another approach with lambda expression.

However, the performance with the use of lambda expression is way worse than the original approach (4x ms vs 1x ms). All the codes in the two program are the same. The only difference is this one line.

Original Code:

list.sort(new Comparator<Map.Entry<Character,Integer>>() 
  {
     @Override
     public int compare(Map.Entry<Character,Integer> o1, Map.Entry<Character,Integer> o2) {
       return o2.getValue().compareTo(o1.getValue());
  }
});

New Code:

list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));
chakwok
  • 980
  • 8
  • 21
  • How did you know about this performance ? – Sambit Jun 01 '19 at 06:31
  • 3
    Because measuring the performance of Java code correctly is a difficult problem. – JB Nizet Jun 01 '19 at 06:31
  • 3
    ^^ see [*How do I write a correct micro-benchmark in Java?*](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – T.J. Crowder Jun 01 '19 at 06:33
  • 4
    Side note: You're re-inventing the wheel. You might as well use the build in [`Map.Entry.comparingByValue()`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html#comparingByValue--) – Mureinik Jun 01 '19 at 06:34
  • @Mureinik I somehow didn't know that was there. Thanks! – chrylis -cautiouslyoptimistic- Jun 01 '19 at 07:03
  • @Sambit This is actually a question on leetcode [link](https://leetcode.com/problems/sort-characters-by-frequency/discuss/302769/java-beats-90.87-using-hashmap) – chakwok Jun 01 '19 at 07:52
  • @T.J.Crowder How would comment on the benchmarking performed behind leetcode? – chakwok Jun 01 '19 at 07:59
  • @JBNizet I have each of them submitted twice on leetcode. Do you think that give a reasonable evaluation on the performance? – chakwok Jun 01 '19 at 08:02
  • @Mureinik Thanks for pointing out that. However, when I try that, the performance is similar to the lambda-way (around 45ms), not as good as the traditional override way(around 1x ms). **My code:** `list.sort(Map.Entry.comparingByValue(Collections.reverseOrder()));` – chakwok Jun 01 '19 at 08:06
  • @Andyk. can you share a link to the leetcode question? – Mureinik Jun 01 '19 at 09:49
  • @Mureinik Sure, [this](https://leetcode.com/problems/sort-characters-by-frequency/discuss/302769/java-beats-90.87-using-hashmap) is the solution I am talking about. – chakwok Jun 01 '19 at 10:27
  • 1
    @Andyk. I edited the duplicate list to point to a more relevant answer - check it out there, it should explain the behavior you're seeing. – Mureinik Jun 01 '19 at 10:38

0 Answers0