Ever wonder which is the fastest way to concatenate strings in Ruby?
No? Too bad!
From this:
require 'benchmark'
Benchmark.bm(20) do |x|
x.report ('<<') do
1_000_000.times do
one = 'one'
two = 'two'
three = 'three'
y = one << two << three
end
end
x.report('+') do
1_000_000.times do
one = 'one'
two = 'two'
three = 'three'
y = one + two + three
end
end
x.report('#{one}#{two}#{three}') do
1_000_000.times do
one = 'one'
two = 'two'
three = 'three'
y = "#{one}#{two}#{three}"
end
end
x.report('one#{two}#{three}') do
1_000_000.times do
two = 'two'
three = 'three'
y = "one#{two}#{three}"
end
end
x.report('onetwo#{three}') do
1_000_000.times do
three = 'three'
y = "onetwo#{three}"
end
end
end
Comes this:
user system total real
<< 4.580000 0.000000 4.580000 ( 4.579776)
+ 5.720000 0.000000 5.720000 ( 5.815782)
#{one}#{two}#{three} 5.180000 0.000000 5.180000 ( 5.185434)
one#{two}#{three} 3.920000 0.000000 3.920000 ( 3.917942)
onetwo#{three} 2.610000 0.000000 2.610000 ( 2.617674)
Thus proving a two things:
- Use
<<for concatenation. It doesn’t make an intermediate copy, unlike+. - If you need to place a string variable inside a chunk of static text, it’s far faster to use interpreted string literals than to concatenate string variables.
Yup.
April 21st, 2006 at 11:21am
How bizarre. I understand why “Joe ” + “and ” + “Monkey” might require intermediate copies, but I would expect Ruby to be smart enough to translate “Joe and ” + “Monkey” into “Joe and “
May 5th, 2007 at 11:34am
[...] En este post realizan un test de rendimiento en las diferentes operaciones de concatenacion de strings en Ruby. [...]
May 5th, 2007 at 1:43pm
Oh dear. Don’t let Zed see this.
Nice idea, but it’s not really statistically meaningful without knowledge of more parameters, environment, standard devs, etc.
July 13th, 2007 at 9:45pm
Results on my laptop show negligible differences between + and
July 13th, 2007 at 9:48pm
For some reason my last comment didn’t post fully, not sure why. I’ll try again…
daniel@octobertop:~/project$ ruby -v && uname -a && ruby test.rb && ruby test.rbruby 1.8.5 (2006-08-25) [x86_64-linux]
Linux octobertop 2.6.20-16-generic #2 SMP Thu Jun 7 19:00:28 UTC 2007 x86_64 GNU/Linux
user system total real