PBP: 099 Sorting

The Best Practices have things to say about many of Perl’s built-in functions.  Besides the general advice “use them” – which I agree with – it has some specific suggestions.  First up: Sorting

The advice given by the PBP regarding sort is not to do complex calculations in the sort function.  That function will be called many times, often calling with a value it has used before.  If you’re doing a complex calculation – say a checksum or other hash – you should cache those calculated values and use the cache.  The PBP has a clear example of this.

It also suggests you could use a Schwartzian Transform to build pre-calculated values, sort on them, then clean up the temporary values.

The third suggestion isn’t made as often, but is quite interesting, and uses a module called Memoize to “memoize” the hash function, which means it will only call it once and store the values – another way of caching.

I agree with the suggestion to avoid complex work when possible in the sort function, as it is called frequently.  Any of these are fine suggestions.

One Response to “PBP: 099 Sorting”

  1. TomM says:

    List::UtilsBy::sort_by (and related functions such as nsort_by, rev_sort_by) tend to make this simpler. Haven’t benchmarked them recently but the XS implementations should still be a viable contender where performance is critical.

Leave a Reply