From: Colin Bartlett Date: 2010-08-05T23:58:19+09:00 Subject: Re: String concatenation in ruby --000e0ce0cda6ad7f6f048d14c7df Content-Type: text/plain; charset=ISO-8859-1 On Thu, Aug 5, 2010 at 2:47 PM, Prachi Tripathi wrote: > Hi, > This seems to be a basic question but i would like to know why. > String concatenation in rails can be done in the following three ways: > 1. a+b+c > 2. a< 3. "#{a}#{b}#{c}" > where a b c are three variables > Which is the good way to go about concatenation and why? > a+b+c is not good because it creates temp string objects i guess > But i would really like to know of the three which is better and why. Is > there any performance difference in using them > Thanks in advance You can experiment using benchmark (see below) or hitimes (which I haven't tried yet), and there may well be others. I think the results should be taken more as indications rather than definitive, but you can see from the following that whether one way is faster than another can depend on the data. (I hope that the formatting of the times is ok - it looks diabolical in this draft.) require "benchmark" r1 = r2 = r3 = nil a = nil av = "Karel Capek".freeze b = " wrote" c = " War with the Newts" kt = 100_000 Benchmark.bmbm do |r| r.report("a+b+c" ) {kt.times { a = av.dup; r1 = a + b + c } } r.report("a< run: "C:\ruby19\bin\ruby.exe" -v "aaa-bm-str.rb" ruby 1.9.1p243 (2009-07-16 revision 24175) [i386-mingw32] Rehearsal ------------------------------------------------ a+b+c 0.405000 0.000000 0.405000 ( 0.470000) a<