Skip to content

Instantly share code, notes, and snippets.

@hamiltop
Created October 1, 2014 05:02
Show Gist options
  • Select an option

  • Save hamiltop/8b32b208a81b277e9ccc to your computer and use it in GitHub Desktop.

Select an option

Save hamiltop/8b32b208a81b277e9ccc to your computer and use it in GitHub Desktop.
defmodule ConcatTest do
def append do
1..10000 |> Enum.reduce([], fn (x, acc) ->
acc ++ [x]
end)
end
def prepend do
1..10000 |> Enum.reduce([], fn (x, acc) ->
[x] ++ acc
end) |> Enum.reverse
end
end
{time, _} = :timer.tc fn -> ConcatTest.append end
IO.puts "Append took #{time}"
{time, _} = :timer.tc fn -> ConcatTest.prepend end
IO.puts "Prepend took #{time}"
@hamiltop

hamiltop commented Oct 1, 2014

Copy link
Copy Markdown
Author
➜  /tmp  elixir append_vs_prepend.exs
Append took 310895
Prepend took 2399

@dch

dch commented Oct 1, 2014

Copy link
Copy Markdown
defmodule ConcatTest do
  def append do
    1..100000 |> Enum.reduce([], fn (x, acc) ->
      acc ++ [x]
    end)
  end
  def prepend do
    1..100000 |> Enum.reduce([], fn (x, acc) ->
      [x] ++ acc
    end) |> Enum.reverse
  end
  def concat do
    1..100000 |> Enum.reduce([], fn (x, acc) ->
      [x | acc]
    end) |> Enum.reverse
  end
  def run do
    {time, _} = :timer.tc fn -> ConcatTest.append end
    IO.puts "Append took #{time}"

    {time, _} = :timer.tc fn -> ConcatTest.prepend end
    IO.puts "Prepend took #{time}"

    {time, _} = :timer.tc fn -> ConcatTest.concat end
    IO.puts "concat took #{time}"
  end
end
iex(4)> ConcatTest.run
Append took 23567395
Prepend took 8995
concat took 7881

interestingly, concat [ a | b] is consistently 10% faster for me. I'd also be interested in memory usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment