Skip to content

Instantly share code, notes, and snippets.

@cr0t
Created August 10, 2024 11:15
Show Gist options
  • Save cr0t/22b4ea4ba4398fbb2739b99146c6378f to your computer and use it in GitHub Desktop.
Save cr0t/22b4ea4ba4398fbb2739b99146c6378f to your computer and use it in GitHub Desktop.
Compare performance of solutions that is based on `case` and uses a Map to get values
Mix.install([:benchee])
defmodule ResistorColor do
@color_map %{
black: 0,
brown: 1,
red: 2,
orange: 3,
yellow: 4,
green: 5,
blue: 6,
violet: 7,
grey: 8,
white: 9
}
def code_via_map(color) do
@color_map[color]
end
def code_via_case(color) do
case color do
:black -> 0
:brown -> 1
:red -> 2
:orange -> 3
:yellow -> 4
:green -> 5
:blue -> 6
:violet -> 7
:grey -> 8
:white -> 9
_ -> nil
end
end
end
input = ~w[black brown red orange yellow green blue violet grey white noneexistent]a
case_res = Enum.map(input, &ResistorColor.code_via_case/1)
map_res = Enum.map(input, &ResistorColor.code_via_map/1)
IO.inspect(case_res == map_res, label: "Both approaches give the same results")
Benchee.run(
%{
"case" => fn -> Enum.map(input, &ResistorColor.code_via_case/1) end,
"map" => fn -> Enum.map(input, &ResistorColor.code_via_map/1) end
},
time: 2,
memory_time: 2,
reduction_time: 2,
print: [fast_warning: false]
)
Both approaches give the same results: true
Operating System: macOS
CPU Information: Apple M3 Pro
Number of Available Cores: 11
Available memory: 18 GB
Elixir 1.17.2
Erlang 27.0.1
JIT enabled: true
Benchmark suite executing with the following configuration:
warmup: 2 s
time: 2 s
memory time: 2 s
reduction time: 2 s
parallel: 1
inputs: none specified
Estimated total run time: 16 s
Benchmarking case ...
Benchmarking map ...
Calculating statistics...
Formatting results...
Name ips average deviation median 99th %
case 12.31 M 81.27 ns ±6986.70% 45.80 ns 141.70 ns
map 4.53 M 220.91 ns ±23389.70% 125 ns 791 ns
Comparison:
case 12.31 M
map 4.53 M - 2.72x slower +139.65 ns
Memory usage statistics:
Name Memory usage
case 176 B
map 176 B - 1.00x memory usage +0 B
**All measurements for memory usage were the same**
Reduction count statistics:
Name Reduction count
case 46
map 68 - 1.48x reduction count +22
**All measurements for reduction count were the same**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment