Skip to content

Instantly share code, notes, and snippets.

@czogori
Last active April 18, 2022 16:05
Show Gist options
  • Save czogori/d498002f3278451b682316614a9345fa to your computer and use it in GitHub Desktop.
Save czogori/d498002f3278451b682316614a9345fa to your computer and use it in GitHub Desktop.
Mix.install([
{:benchee, "~> 1.0"}
])
defmodule TestRecursion do
def sum([]), do: 0
def sum([h|t]), do: h + sum(t)
end
defmodule TestTailRecursion do
def sum(list, acc \\ 0)
def sum([], acc), do: acc
def sum([h|t], acc), do: sum(t, acc + h)
end
list = Stream.repeatedly(fn -> :rand.uniform(50) end) |> Enum.take(10_000)
Benchee.run(
%{
"sum recursion" => fn -> TestRecursion.sum(list) end,
"sum tail recursion" => fn -> TestTailRecursion.sum(list) end
},
time: 10,
memory_time: 2
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment