Sep 29
A lot of developers know the dangers of concatenation with Strings and objects. In Java we had the StringBuffer.append vs. + (and now StringBuilder) knowledge transfer.
Ruby has the same issue, and people have talked about it before.
We ran into this issue in one of our projects, and I remember Dave Thomas talk about a problem that was fixed by moving from string concatenation to putting the contents on an array.
I think this benchmark says it all:
require 'benchmark' Benchmark.bm do |x| x.report do a = 'foo' 100000.times { a += ' foo' } end x.report do a = 'foo' 100000.times { a << ' foo' } end end
Output
dion@stewart [~]$ ruby t.rb user system total real 13.790000 25.180000 38.970000 ( 40.102451) 0.060000 0.000000 0.060000 ( 0.064342)
So, favour << unless you really want to copy strings around.
September 29th, 2006 at 2:32 pm
I’m not really sure this is an “issue”. You need both behaviors or someone will scream.
This is pretty old news, btw.
- Dan
September 29th, 2006 at 3:05 pm
You definitely do need both.
I also know this is old, but a lot of new ruby programmers have been caught on this one recently.
It is much more intuitive to do “foo” + “bar” for many new rubyists, and they do not know the downside (until it hits them).
Dion
October 2nd, 2006 at 12:06 pm
Java also tries to help you out by converting chains of + concats to StringBuilder under the hoods when compiling. Doesn’t help the looping example you have above, but works on stuff like:
String s = “foo” + s1 + “bar” + s2 + “baz” + s3;
This creates the same number and type of Objects as:
StringBuilder sb = new StringBuilder();
sb.append(”foo”).append(s1).append(”bar”).append(s2).append(”baz”).append(s3);
String s = sb.toString();
July 20th, 2008 at 2:16 pm
thanks for your share,very good.thnaks!
November 1st, 2008 at 10:02 am
http://almaer.com/blog/emotional-hedging#comment-39836
November 8th, 2008 at 7:39 am
http://www.batteryfast.com/acer/travelmate-2000.htm acer travelmate 2000 battery,
November 10th, 2008 at 5:33 am
http://www.batteryfast.co.uk/dell/inspiron-1150.htm dell inspiron 1150 battery,
November 14th, 2008 at 8:30 pm
http://www.batteryfast.com/laptop-ac-adapter/dell/DELL-19.5V-4.62A-90W-pin.php AC Adapter 4 Dell Inspiron 9T215 19.5V 4.62A 90W PA10
November 17th, 2008 at 9:30 pm
http://www.batteryfast.com/toshiba/1800.htm toshiba 1800 battery,
November 21st, 2008 at 8:31 pm
http://www.batteryfast.co.uk/asus/m3000-silver.htm asus m3000 silver battery,
November 23rd, 2008 at 9:25 pm
http://www.batteryfast.co.uk/asus/m5n.htm asus m5n battery,
May 31st, 2010 at 5:37 am
Ajax script apply, please refer http://www.battery-shop.org , the battery price loading by Ajax