Skip to content

Instantly share code, notes, and snippets.

@cr0t
Created February 9, 2024 20:26
Show Gist options
  • Save cr0t/00a6c31cac4cc5a6b0b1270c0f29d418 to your computer and use it in GitHub Desktop.
Save cr0t/00a6c31cac4cc5a6b0b1270c0f29d418 to your computer and use it in GitHub Desktop.
Just a few benchmarks to compare concatenation (<>), interpolation, joining, and IO lists performances in Elixir
Mix.install([:benchee])
defmodule StringPerf do
def concat([]), do: ""
def concat([head | tail]), do: head <> concat(tail)
def interpol([]), do: ""
def interpol([head | tail]), do: "#{head}#{interpol(tail)}"
def joiner(input), do: Enum.join(input, "")
def io(input), do: IO.iodata_to_binary(input)
end
# build just a list of stringified numbers
input = Enum.map(1..10_000, &Integer.to_string/1)
# check that all the functions from above return the same result
IO.inspect([
StringPerf.concat(input) == StringPerf.interpol(input),
StringPerf.interpol(input) == StringPerf.joiner(input),
StringPerf.joiner(input) == StringPerf.io(input)
], label: "===> All functions return the same result")
# benchmark the performance!
Benchee.run(
%{
"concatenation" => fn -> StringPerf.concat(input) end,
"interpol" => fn -> StringPerf.interpol(input) end,
"join" => fn -> StringPerf.joiner(input) end,
"io" => fn -> StringPerf.io(input) end
},
time: 5,
memory_time: 5
)
$ elixir string_bench.exs
===> All functions return the same result: [true, true, true]
Operating System: macOS
CPU Information: Apple M3 Pro
Number of Available Cores: 11
Available memory: 18 GB
Elixir 1.16.1
Erlang 26.2.1
JIT enabled: true
Benchmark suite executing with the following configuration:
warmup: 2 s
time: 5 s
memory time: 5 s
reduction time: 0 ns
parallel: 1
inputs: none specified
Estimated total run time: 48 s
Benchmarking concatenation ...
Benchmarking interpol ...
Benchmarking io ...
Benchmarking join ...
Calculating statistics...
Formatting results...
Name ips average deviation median 99th %
io 16.60 K 0.0603 ms ±7.86% 0.0597 ms 0.0688 ms
join 6.33 K 0.158 ms ±14.11% 0.150 ms 0.22 ms
interpol 0.23 K 4.30 ms ±7.55% 4.27 ms 5.41 ms
concatenation 0.23 K 4.37 ms ±8.35% 4.29 ms 5.58 ms
Comparison:
io 16.60 K
join 6.33 K - 2.62x slower +0.0977 ms
interpol 0.23 K - 71.42x slower +4.24 ms
concatenation 0.23 K - 72.53x slower +4.31 ms
Memory usage statistics:
Name Memory usage
io 0.0469 KB
join 156.30 KB - 3334.33x memory usage +156.25 KB
interpol 859.29 KB - 18331.50x memory usage +859.24 KB
concatenation 859.29 KB - 18331.50x memory usage +859.24 KB
**All measurements for memory usage were the same**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment