Created
August 13, 2024 16:12
-
-
Save lunks/2a93b7f710e7de7444b45883288a0d3e to your computer and use it in GitHub Desktop.
recursion vs while/reduce elixir benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule BenchmarkReduceWhile do | |
def has_duplicates?(list) do | |
Enum.reduce_while(list, %MapSet{}, fn x, seen -> | |
if MapSet.member?(seen, x) do | |
{:halt, true} | |
else | |
{:cont, MapSet.put(seen, x)} | |
end | |
end) || false | |
end | |
end | |
defmodule BenchmarkRecursion do | |
def has_duplicates?(list), do: has_duplicates?(list, %MapSet{}) | |
defp has_duplicates?([], _), do: false | |
defp has_duplicates?([head | tail], seen) do | |
MapSet.member?(seen, head) || has_duplicates?(tail, MapSet.put(seen, head)) | |
end | |
end | |
defmodule BenchmarkTest do | |
def run do | |
list = Enum.to_list(1..10000) ++ [5000] | |
Benchee.run( | |
%{ | |
"reduce_while" => fn -> BenchmarkReduceWhile.has_duplicates?(list) end, | |
"recursion" => fn -> BenchmarkRecursion.has_duplicates?(list) end | |
}, | |
time: 20, | |
warmup: 5 | |
) | |
end | |
end | |
BenchmarkTest.run() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Operating System: Linux | |
CPU Information: AMD Ryzen Threadripper 3970X 32-Core Processor | |
Number of Available Cores: 32 | |
Available memory: 16 GB | |
Elixir 1.16.2 | |
Erlang 26.2.5 | |
JIT enabled: true | |
Benchmark suite executing with the following configuration: | |
warmup: 5 s | |
time: 20 s | |
memory time: 0 ns | |
reduction time: 0 ns | |
parallel: 1 | |
inputs: none specified | |
Estimated total run time: 50 s | |
Benchmarking recursion ... | |
Benchmarking reduce_while ... | |
Calculating statistics... | |
Formatting results... | |
Name ips average deviation median 99th % | |
recursion 404.36 2.47 ms ±13.41% 2.38 ms 3.52 ms | |
reduce_while 372.01 2.69 ms ±12.97% 2.53 ms 3.65 ms | |
Comparison: | |
recursion 404.36 | |
reduce_while 372.01 - 1.09x slower +0.22 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment