Skip to content

Instantly share code, notes, and snippets.

@teeparham
Last active January 29, 2019 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teeparham/434577d58ce486b69e68cc0602d66d03 to your computer and use it in GitHub Desktop.
Save teeparham/434577d58ce486b69e68cc0602d66d03 to your computer and use it in GitHub Desktop.
Ruby multi-line string performance
require "benchmark"
require "active_support/core_ext/string/strip"
n = 10_000
Benchmark.bm do |bm|
bm.report("string") do
n.times do
"hello\nthere\nbear"
end
end
bm.report("array") do
n.times do
["hello", "there", "bear"].join("\n")
end
end
bm.report("heredoc") do
n.times do
<<-HERE
hello
there
bear
HERE
end
end
# !!!!!!
bm.report("tilde heredoc") do
n.times do
<<~HERE
hello
there
bear
HERE
end
end
bm.report("strip heredoc") do
n.times do
<<-HERE.strip_heredoc
hello
there
bear
HERE
end
end
bm.report("strip heredoc nodash") do
n.times do
<<HERE.strip_heredoc
hello
there
bear
HERE
end
end
end
# sorted results (ruby 2.6.0)
# user system total real
# tilde heredoc 0.000661 0.000124 0.000785 ( 0.000796)
# string 0.001885 0.000134 0.002019 ( 0.002053)
# heredoc 0.001981 0.000056 0.002037 ( 0.002100)
# array 0.009141 0.000597 0.009738 ( 0.009806)
# strip heredoc nodash 0.111129 0.005337 0.116466 ( 0.121615)
# strip heredoc 0.114132 0.006298 0.120430 ( 0.130637)
# sorted results (ruby 2.4.3)
# user system total real
# heredoc 0.000000 0.000000 0.000000 ( 0.002136)
# tilde heredoc 0.000000 0.000000 0.000000 ( 0.002205)
# string 0.010000 0.000000 0.010000 ( 0.002565)
# array 0.020000 0.000000 0.020000 ( 0.019595)
# strip heredoc nodash 0.120000 0.000000 0.120000 ( 0.120830)
# strip heredoc 0.110000 0.000000 0.110000 ( 0.124549)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment