Optimising for performance in Elm, Pt. 4

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

So, let’s have a look at these three and compare their performance with a micro-benchmark:https://medium.com/media/343a8d9455797ebe7a468e62cd447448/hrefNote that this is just a group of benchmarks, since there’s no sane way to do three-way compares right now.On my machine, the naive implementation is the fastest (by a fairly minor margin), with the TCO implementation being the slowest one, and TCO+Bitwise version hovering in between. Note that the number of recursions required is proportional to the input size. On my machine, though, even with large inputs, the TCO version would only be about on-par with the non-TCO version.It does offer us some useful information, though — we could combine the naive approach with the Bitwise operators.There’s another avenue of improvement: the digit function is doing a String.slice call, which is backed by native JavaScript String.slice but still comes at a cost. We could approach the issue in a slightly different way: if n < 10 , we can simply toString it. If n >= 10 we could simply have a case..of expression for the remaining cases; in which each branch would be doing an equality check to a constant number.Finally, we’re computing n % 16 even when there is nothing left to do. This seems minor, but moving that piece of modulo math into the digit function does buy us some extra performance.Let’s stack our performance-optimised version against the original (much more legible) version by unsoundscapes, for a couple of different sizes:https://medium.com/media/d8be944480872455f0f56cc87fb79312/hrefYay, numbers!Takeaways:

Optimising for performance in Elm, Pt. 4 was originally published in Ilias Van Peer on Medium, where people are continuing the conversation by highlighting and responding to this story.