0

I'm writing an external sort in Java, using the N-way merge algorithm from this question. That involves adding and polling pairs of integers to and from a java.util.PriorityQueue. Currently, I'm using AbstractMap.SimpleImmutableEntry for the pairs, but that's actually slower than my previous non-priority-queue approach (even though it's asymptotically faster)! Is there a faster pair class available, or should I write my own? I need pairs of integers that can be sorted by the first one, but apart from that the only thing that matters is speed. To clarify, the code isn't unreasonably slow (it's not surprising that the priority queue approach isn't much faster, given that while the asymptotic complexity goes from O(MN) to O(M log N), N is quite small), I just feel like making it as fast as possible.

rlms
  • 9,314
  • 8
  • 37
  • 58
  • 3
    By integers, do you mean int, or Integer? What makes you think that the Pair class is what makes your code slow? – JB Nizet Aug 31 '17 at 19:35
  • You don't need any "physical" pair for that of course, but likely that's the only way to shoe-horn it into a built-in collection. – harold Aug 31 '17 at 19:36
  • Faster in what respect? What's so slow about `SimpleImmutableEntry`? – Radiodef Aug 31 '17 at 19:47
  • @JBNizet int, but I assume that an inbuilt solution would probably use Integer. I think the choice of pair class is likely a good thing to optimise because there's a clear choice for which implementation of priority queue to use but no clear choice for the pair class. Looking at a profiler, most of the time not spent doing IO is spent using the comparator of the priority and doing Integer.valueOf (IO is the main factor, but not what I'm currently interested in optimising). – rlms Aug 31 '17 at 19:49
  • 4
    If you know that you need primitive ints, and that a large part of the code is spent in Integer.valueOf(), then write a simple Pair class storing primitive ints rather than Integers, and you won't have all these boxings anymore. – JB Nizet Aug 31 '17 at 19:51
  • _I just feel like making it as fast as possible_. Sounds like [premature optimization](http://wiki.c2.com/?PrematureOptimization) to me. – Andreas Aug 31 '17 at 20:01
  • @Andreas The context is that it's university work, where there is no advantage to be gained from increasing speed, but there is a public leaderboard and therefore some friendly competition. – rlms Aug 31 '17 at 20:08

0 Answers0