Skip to content

Instantly share code, notes, and snippets.

@yb66
Forked from alno/bench_str_building.rb
Last active March 20, 2019 05:06
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 yb66/91e4cc63168d60ca732856afcde345fc to your computer and use it in GitHub Desktop.
Save yb66/91e4cc63168d60ca732856afcde345fc to your computer and use it in GitHub Desktop.
Benchmark: interpolation vs concatenation in Ruby
require 'benchmark'
count = 1_000_000
Benchmark.bmbm do |bm|
bm.report("to_s + ") { count.times { 11.to_s + '/' + 12.to_s } }
bm.report("+ ") { count.times { "11" + '/' + "12" } }
bm.report('#{} to_s ') { count.times { "#{11}/#{12}" } }
bm.report('#{} ') { count.times { %Q!#{"11"}/#{"12"}! } }
bm.report("to_s << ") { count.times { 11.to_s << "/" << 12.to_s } }
bm.report("<< ") { count.times { "11" << "/" << "12" } }
bm.report("StringIO ") {
count.times do
s = StringIO.new
s << "11"
s << "/"
s << "12"
s.string
end
}
bm.report("map join ") { count.times { [11, 12].map(&:to_s).join("/") } }
bm.report("to_s join") { count.times { [11.to_s, 12.to_s].join("/") } }
bm.report("join ") { count.times { ["11", "12"].join("/") } }
end
@yb66
Copy link
Author

yb66 commented Mar 20, 2019

$ ruby ~/Scripts/bench_str_building.rb 
Rehearsal ---------------------------------------------
to_s +      0.389054   0.000582   0.389636 (  0.390258)
+           0.274558   0.000684   0.275242 (  0.276235)
#{} to_s    0.382394   0.000893   0.383287 (  0.384348)
#{}         0.076470   0.000274   0.076744 (  0.077115)
to_s <<     0.373929   0.000914   0.374843 (  0.376104)
<<          0.245698   0.000761   0.246459 (  0.248505)
StringIO    1.110651   0.003397   1.114048 (  1.119766)
map join    0.959411   0.002280   0.961691 (  0.964836)
to_s join   0.768819   0.001716   0.770535 (  0.772899)
join        0.646993   0.001805   0.648798 (  0.652086)
------------------------------------ total: 5.241283sec

                user     system      total        real
to_s +      0.392656   0.001168   0.393824 (  0.395837)
+           0.270662   0.000861   0.271523 (  0.272625)
#{} to_s    0.378121   0.000852   0.378973 (  0.380216)
#{}         0.076828   0.000321   0.077149 (  0.077619)
to_s <<     0.372846   0.001030   0.373876 (  0.375117)
<<          0.242815   0.000605   0.243420 (  0.244143)
StringIO    1.097562   0.002471   1.100033 (  1.104226)
map join    0.939145   0.002216   0.941361 (  0.944511)
to_s join   0.776274   0.002178   0.778452 (  0.781472)
join        0.634289   0.001305   0.635594 (  0.637624)

If you already have a string then #{} and << are the clear winners. If not, .to_s will kill any significant difference but << has the slight edge.

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