Concatenating strings

I was looking at some podcasts and Ryan is using an interesting way to concatenate 2 strings, using an array and a join operation.

def full_name
  [first_name, last_name].join(' ')

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(' ')

def using_format(a,b)
  "#{a} #{b}"

def using_concat(a,b)
  a+' '+b

Benchmark.benchmark " "*7 + CAPTION, 7, FMTSTR do |x|
  a = 'We all'
  b = 'love Ruby on Rails'

  n = 300000"Array: ") { n.times do; using_array(a,b); end }"Format:") { n.times do; using_format(a,b); end }"Concat:") { n.times do; using_concat(a,b); 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.


One thought on “Concatenating strings

  1. If Ryan’s model allows for either name to be nil, then his method has the benefit of eliminating a terminal space, which (aside from aesthetics) would be significant if any sorting is being done on the full_name method.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s