I was looking at some Railscasts.com podcasts and Bryan is using an interesting way to concatenate 2 strings, using an array and a join operation.
def full_name
[first_name, last_name].join(' ')
end
Now, I was wondering if this was a bit overkill since it has to allocate an Array, then loop through it and build the string. So I ran Benchmark on three different ways to concatenate.
require 'benchmark'
include Benchmark
def using_array(a,b)
[a,b].join(' ')
end
def using_format(a,b)
"#{a} #{b}"
end
def using_concat(a,b)
a+' '+b
end
Benchmark.benchmark " "*7 + CAPTION, 7, FMTSTR do |x|
a = 'We all'
b = 'love Ruby on Rails'
n = 300000
x.report("Array: ") { n.times do; using_array(a,b); end }
x.report("Format:") { n.times do; using_format(a,b); end }
x.report("Concat:") { n.times do; using_concat(a,b); end }
end
And the results speaks for themselves. As in other languages, the less memory allocations you do, the more performance you will get.
user system total real
Array: 1.810000 0.020000 1.830000 ( 2.395285)
Format: 1.450000 0.010000 1.460000 ( 1.634995)
Concat: 1.670000 0.020000 1.690000 ( 1.974156)
As you can see, using the format string is really a better approach and I find it easier to read as well.







