-
-
Save yb66/91e4cc63168d60ca732856afcde345fc to your computer and use it in GitHub Desktop.
Benchmark: interpolation vs concatenation in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.