Skip to content

Instantly share code, notes, and snippets.

@ssut
Last active August 29, 2015 13:59
Show Gist options
  • Save ssut/10631194 to your computer and use it in GitHub Desktop.
Save ssut/10631194 to your computer and use it in GitHub Desktop.
Ruby String Concatenation Performance Test ('<<' operator vs '+' operator vs interpolation) http://ssut-dev.tumblr.com/post/82675129445/ruby-string-concatenation-ruby-2-1-1
require 'benchmark'
N = 10_000
LENGTH = 100
STR1, STR2, STR3 = "a", "b" * LENGTH, "c"
puts "LENGTH: " << (STR1.size + STR2.size + STR3.size).to_s
Benchmark.bm(10) do |x|
x.report('"" < STR1 << STR2 << STR3') do
N.times do
y = '' < STR1 << STR2 << STR3
end
end
x.report('STR1 + STR2 + STR3') do
N.times do
y = STR1 + STR2 + STR3
end
end
x.report('#{STR1}#{STR2}#{STR3}') do
N.times do
y = "#{STR1}#{STR2}#{STR3}"
end
end
x.report('[STR1, STR2, STR3].join') do
N.times do
y = [STR1, STR2, STR3].join
end
end
end
- OS X 10.9 Mavericks / RubyENV(rbenv) 2.1.1-p76 -
LENGTH: 102
user system total real
"" < STR1 << STR2 << STR3 0.000000 0.010000 0.010000 ( 0.005643)
STR1 + STR2 + STR3 4.320000 6.910000 11.230000 ( 11.255716)
#{STR1}#{STR2}#{STR3} 2.450000 5.930000 8.380000 ( 8.377277)
[STR1, STR2, STR3].join 2.080000 3.710000 5.790000 ( 5.886817)
- Ubuntu 13.10 / RubyENV(rbenv) 2.1.1-p76 -
LENGTH: 102
user system total real
"" < STR1 << STR2 << STR3 0.010000 0.000000 0.010000 ( 0.004026)
STR1 + STR2 + STR3 2.270000 0.260000 2.530000 ( 2.531887)
#{STR1}#{STR2}#{STR3} 1.230000 1.530000 2.760000 ( 2.781068)
[STR1, STR2, STR3].join 0.970000 0.060000 1.030000 ( 1.015118)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment