Untitled notebook
Mix.install([:benchee])
Section
defmodule ParseInt do
def parse_new(<<3::4, x0::4, 3::4, x1::4, 3::4, x2::4, 3::4, x3::4>>)
when x0 < 10 and x1 < 10 and x2 < 10 and x3 < 10 do
x3 + x2 * 10 + x1 * 100 + x0 * 1000
end
def nimble(<>)
when x0 >= 48 and x0 <= 57 and (x1 >= 48 and x1 <= 57) and
(x2 >= 48 and x2 <= 57) and (x3 >= 48 and x3 <= 57) do
x3 - 48 + (x2 - 48) * 10 + (x1 - 48) * 100 + (x0 - 48) * 1000
end
end
{ParseInt.parse_new("1123"), ParseInt.nimble("1123")}
list = Enum.map(1000..9999, &to_string(&1))
Benchee.run(
%{
"original" => fn -> Enum.map(list, &ParseInt.nimble(&1)) end,
"half byte" => fn -> Enum.map(list, &ParseInt.parse_new(&1)) end
},
time: 10,
memory_time: 2
)