From: Robert Dober Date: 2007-08-24T17:19:09+09:00 Subject: Re: something I just found out, am sharing (:newbish) On 8/24/07, Simon Schuster wrote: > 075:0> a = "hello" > "hello" > 076:0> a += " there." > "hello there." > 077:0> > > > neat! not really :( a += " there" is a = a + " there" a << " there" I might be accused of premature optimizationism (A word I just made up, I have to make an ECR ;). But seriously there is just no need to pay the cost of the construction of another String / Array. Performance difference is already enormous for moderately long strings : 511/11 > cat costs.rb # vim: sw=2 sts=2 ft=ruby expandtab tw=0: require 'benchmark' N = ARGV.first.to_i a = "Hello Nice Little " Benchmark.bmbm do |mybench| mybench.report(" += "){ N.times{ a += "." } } mybench.report(" << "){ N.times{ a << "." } } end # Benchmark.bmbm do robert@PC:~/log/ruby/ML 10:17:57 512/12 > ruby costs.rb 1000 Rehearsal ---------------------------------------- += 0.000000 0.000000 0.000000 ( 0.002936) << 0.000000 0.000000 0.000000 ( 0.001008) ------------------------------- total: 0.000000sec user system total real += 0.000000 0.010000 0.010000 ( 0.080035) << 0.000000 0.000000 0.000000 ( 0.000927) robert@PC:~/log/ruby/ML 10:18:04 513/13 > ruby costs.rb 10000 Rehearsal ---------------------------------------- += 0.160000 0.020000 0.180000 ( 0.565431) << 0.010000 0.000000 0.010000 ( 0.012393) ------------------------------- total: 0.190000sec user system total real += 0.730000 0.050000 0.780000 ( 0.826307) << 0.010000 0.000000 0.010000 ( 0.013734) robert@PC:~/log/ruby/ML 10:18:08 514/14 > ruby costs.rb 20000 Rehearsal ---------------------------------------- += 0.620000 0.010000 0.630000 ( 0.741340) << 0.030000 0.000000 0.030000 ( 0.077221) ------------------------------- total: 0.660000sec user system total real += 3.060000 0.000000 3.060000 ( 3.131026) << 0.030000 0.000000 0.030000 ( 0.076420) robert@PC:~/log/ruby/ML 10:18:20 515/15 > ruby costs.rb 30000 Rehearsal ---------------------------------------- += 1.380000 0.020000 1.400000 ( 1.452444) << 0.040000 0.000000 0.040000 ( 0.087939) ------------------------------- total: 1.440000sec user system total real += 6.760000 0.040000 6.800000 ( 6.848208) << 0.040000 0.000000 0.040000 ( 0.036871) Cheers Robert > > -- I'm an atheist and that's it. I believe there's nothing we can know except that we should be kind to each other and do what we can for other people. -- Katharine Hepburn