Performance Analysis of Scala List Sort
The default behavior of the scala list sortBy operation is sorting in the ascending order. To get the descending order, the options are simple a) sortBy with default behavior and then reverse the list or b) provide an explicit ordering function.
The first option has obvious disadvantages over the second option: O(nlogn) operation followed by another O(n) operation and poor readability aspects; providing explicit ordering function provides reader clarity on expected outcome. To test out the performance, I wrote a simple scala code.
Here are the performance results over 25 simulation runs.
|List Length||Mean Difference
For lists of sizes greater than million elements, it becomes obvious that the second option with explicitly provided ordering operator is a better choice. For smaller lists, like the typical ones we interact with on a daily basis in production, either option seems to work well.