jdfrens
10/3/2017 - 4:35 PM

Elixir performance writing file with joined newlines

The results may surprise you!

defmodule ExperimentBench do
  use Benchfella

  @list Enum.to_list(1..500_000) |> Enum.map(&to_string/1)

  bench "IO.puts" do
    file = File.open!("/tmp/puts.txt", [:write])
    Enum.each(@list, &(IO.puts file, &1))
    File.close(file)
  end

  bench "IO.write join" do
    file = File.open!("/tmp/write-join.txt", [:write])
    IO.write file, Enum.join(@list, "\n")
    File.close(file)
  end

  bench "IO.write interspersed" do
    file = File.open!("/tmp/write-intersperse.txt", [:write])
    IO.write file, Enum.intersperse(@list, "\n")
    File.close(file)
  end
end