Optimising a toHex functionThe other day, someone on the Elm-lang Slack asked for an (efficient) toHex : Int -> String implementation. Of course, efficiency shouldn’t be the primary concern when doing something like that - fredcy/elm-parseint already provides some very nice functions that cover this, as well as a plethora of other int <-> string conversions with different radixes.Nevertheless, @unsoundscapes jumped to the rescue, and tried a couple of different implementations:
- an initial, “naive” implementation
- a tail call optimised variation
- a second TCO variation using Bitwise operators
- Some optimisations work better for smaller inputs, some optimisations work better for larger inputs. Try to benchmark different cases and keep the real-world use cases in mind.
- Be lazy: don’t calculate what you don’t need.
- Benchmark, benchmark, benchmark. You can’t know with absolute certainty if something will be faster until you have benchmarks to back it up.
- If a function has a limited domain of possible inputs, it might be a candidate for optimisation.
- Part 1: Introduction
- Part 2: Optimising the foldl operation in a recursive data structure
- Part 3: Optimising the rebalancing operation in a self-balancing search tree
- Part 4: Optimising a toHex function
- Part 5: Pitfalls you may run into