Elixir: Fast list concat

Posted on May 22, 2023
Tags: elixir

If you are concating two lists xs & ys in elixir you can use the operator ++. If you don’t care about the order of the result you should put the smaller list first, i.e.: smaller_list ++ larger_list

ys = Enum.to_list(0..1000)
xs = Enum.to_list(0..100_000)

Benchee.run(%{
  "native, larger first" => fn ->
    xs ++ ys
  end,
  "native, smaller first" => fn ->
    ys ++ xs
  end
})
mix run lib/benchee/conact.exs
Operating System: macOS
CPU Information: Apple M1 Pro
Number of Available Cores: 10
Available memory: 16 GB
Elixir 1.14.4
Erlang 25.3.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 native, larger first ...
Benchmarking native, smaller first ...

Name                            ips        average  deviation         median         99th %
native, smaller first      645.67 K        1.55 μs  ±1138.68%        1.21 μs        5.50 μs
native, larger first         3.59 K      278.26 μs   ±152.66%         128 μs     1019.67 μs

Comparison:
native, smaller first      645.67 K
native, larger first         3.59 K - 179.67x slower +276.71 μs