When would you need to append to an Elixir list over prepending?

As I continue learn Elixir, I learned that appending to an Elixir list is much slower compared to prepending. That said in what causes would appending (or inserting) into an Elixir list be necessary over prepending the item?

When the new item strictly belongs to a place that is not the head, eg in a ordered list of names you can’t simply cons "Zertakis" to the front.

In general it massively depends on the use case you have.

In most cases consing is enough though.

1 Like

Maybe when you want to build an iolist.

defmodule Test do
  @spec prepend(integer) :: :ok
  def prepend(count) do
    prepend(["a" | "a"], count)
  @spec prepend(iolist, integer) :: iolist
  def prepend(acc, 0), do: acc
  def prepend(acc, count) do
    prepend([acc | "a"], count - 1)
# prepends "a" to previous iolists 1000 times in 34 microseconds
iex(3)> :timer.tc fn -> Test.prepend(1000) end
{34, :ok}

That’s how web servers in erlang usually build their responses. Not many functions outside of IO modules accept iolists though.

1 Like