Created
November 15, 2022 22:30
-
-
Save cr0t/503a34dda415cdaa00b2063c64efabe0 to your computer and use it in GitHub Desktop.
Performance comparison between `cond` and multiple-clauses functions in Elixir
This file contains 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
Mix.install([ | |
{:benchee, "~> 1.0"} | |
]) | |
defmodule BirdCond do | |
def busy_days(list) do | |
cond do | |
list == [] -> 0 | |
hd(list) < 5 -> busy_days(tl(list)) | |
true -> 1 + busy_days(tl(list)) | |
end | |
end | |
def run(count) do | |
list = 1..count |> Enum.to_list() | |
1..count |> Enum.each(fn _ -> busy_days(list) end) | |
end | |
end | |
defmodule BirdPattern do | |
def busy_days([]), do: 0 | |
def busy_days([day_n | tail]) when day_n >= 5, do: 1 + busy_days(tail) | |
def busy_days([_ | tail]), do: 0 + busy_days(tail) | |
def run(count) do | |
list = 1..count |> Enum.to_list() | |
1..count |> Enum.each(fn _ -> busy_days(list) end) | |
end | |
end | |
count = 10_000 | |
Benchee.run(%{ | |
"cond" => fn -> BirdCond.run(count) end, | |
"patt" => fn -> BirdPattern.run(count) end | |
}) | |
# Example run: | |
# | |
# $ elixir cond_vs_pattern.exs | |
# Operating System: macOS | |
# CPU Information: Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz | |
# Number of Available Cores: 12 | |
# Available memory: 32 GB | |
# Elixir 1.14.1 | |
# Erlang 25.1.2 | |
# | |
# Benchmark suite executing with the following configuration: | |
# warmup: 2 s | |
# time: 5 s | |
# memory time: 0 ns | |
# reduction time: 0 ns | |
# parallel: 1 | |
# inputs: none specified | |
# Estimated total run time: 14 s | |
# | |
# Benchmarking cond ... | |
# Benchmarking patt ... | |
# | |
# Name ips average deviation median 99th % | |
# cond 2.19 457.24 ms ±2.58% 456.92 ms 473.56 ms | |
# patt 2.02 494.53 ms ±3.59% 499.45 ms 520.28 ms | |
# | |
# Comparison: | |
# cond 2.19 | |
# patt 2.02 - 1.08x slower +37.30 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment