elixir-lang/elixir — pull request #2910 by mroth (2014-12-02 01:14:32+00:00)
Title: Introduce an efficient implementation for Integer.digits/1

Most programmers tend to implement the digits of an integer by converting to a string representation, splitting the string, and then converting each char back into an integer. E.g. with code such as the following:

```elixir
# BAD CODE - DONT DO THIS
def digits(n) when is_integer(n) and n>0 do
n
|> Integer.to_string
|> String.graphemes
|> Enum.map(&String.to_integer/1)
end
```
Which results in a lot of inefficient type conversion and memory allocations.

In contrast, this implementation is purely mathematical. In informal benchmarks on my workstation, it performs at **0.9 μs/op** versus **4.8 μs/op** in the naïve implementation above. Plus, it will handle negative numbers properly, which most String solutions mess up.

While this is a pretty basic function, the way that 9/10 programmers tend to implement it is very inefficient and error prone, and it is in common usage. Thus, I would suggest that having a proper and efficient implementation in the standard lib is desirable.