Concatenating strings

I was looking at some Railscasts.com 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(' ')
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.

Advertisements

Railscasts rocks!

Another great discovery: railscasts.com. Over 73 small video podcats on different hints for Ruby on Rails. If you are a beginner or a senior RoR developper, you will for sure learn something from those podcasts. They are also accessible through iTunes, so you can subscribe to the podcast and have them sent to your iPod or iPhone. Thanks to Francois Beausoleil for the hint.

Google Trends

Wow.. amazing. Somedays, I just love Google. I just discovered Google Trends this morning. Check the Ruby on Rails trend. Isn’t that amazing? Now, you see on this graph that the trend is stable for now. I personally thought it would be going up, but hey, that’s just because I LOVE RoR.

RoR Trend

Now what happens if we compare with other web development frameworks? Let’s combine the results with PHP, ASP.Net, Python, Java.

Interesting. Of course, Java is the highest one, followed by PHP. But if you look closely, you’ll notice that they are all going down. Although the new kid on the block (Ruby on Rails) is not as popular as the others, it’s popularity is not declining.

Yesterday, I was looking at Joomla and Drupal. Both open source CMS are getting a lot of attention. But I hear more often about Joomla than Drupal. Let’s see if this reflects in Google Trends! Of course, it does.

Have fun with Google Trends. It might not be scientific bullet-proof statistics, but since we are almost all using Google for our searches, I think we can rely on those facts.