I was working on the Luhn algorithm exercise on Exercism and took two approaches to the problem. Then I benchmarked them. I am curious to hear about which approach you would assume performed better.
As background (simplifying a bit), the algorithm involves:
- Starting with a string of presumably digits and spaces
- Strip the spaces
- Perform a calculation on each number (which calculation depends on position in the stripped string)
- Sum up the transformed numbers
- Take the remainder of the sum divided by 10
My first approach was to strip the spaces, convert the number to a charlist then a list of integers, and traverse the list of digits to do the transformation, then Enum.sum/1 and divide.
My second approach was to strip the spaces, and recursively process the string by binary pattern-matching on the first character, performing the applicable calculation and accumulating a sum, then divide.
Which of these approaches would you expect to perform better in a simple Benchee-style test?
I am curious to hear what people think; if anyone is interested enough to respond with their reasoned take I’ll post the results (and the code so you can tell me what I did wrong either in the slower case or the benchmarking).


















