views:

98

answers:

4

Such as

var myName = 'Bob';
myName += ' is a good name';

For long operations of this, it there a better way to do it? Maybe with a StringBuffer type of structure?

Thanks! :)

+4  A: 

The ‘better’ way would be:

var nameparts= ['Bob'];
nameparts.push(' is a good name');
...
nameparts.join('');

However, most modern JavaScript implementations do now detect naïve concatenation and can in many cases optimise it away, because so many people have (alas) written code this way. So in practice the ‘good’ method won't today be as much faster as it once was.

bobince
Right - I think it's a shame to mess up lovely code with narrowly-focused optimization techniques. Now, that said, IE6 was really so horribly slow in some situations that this particular trick is one that's really good to know. For two or three concatenations it's silly, but for numbers as low as the low hundreds it can make a surprising difference.
Pointy
Do you have a list of the implementations that optimize this away?
bobber205
I am modifying some some older JS code and the function that took 40% of the execution time according to Firebug is mostly just string concatenations.
bobber205
+1  A: 

Huge performance boost can be obtained by simply using intermediate strings! It is possible to create StringBuffer-like class in JavaScript to gain even more performance boost.

See the complete article and graphs here.

Tom Brito
A: 

I once read an article about this subject which offerer some code to build buffered strings with arrays:

http://www.softwaresecretweapons.com/jspwiki/javascriptstringconcatenation

I tested it myself and it was way faster in IE... and way slower in Firefox!

To sum up: there're many JavaScript engines out there and we can't really rely on this sort of implementation details. If it's ever an issue, you'll notice. Before that, don't care too much.

Álvaro G. Vicario
+1  A: 

Efficiency of string concatenation will depend on a browser you are using. You can google for statistics, there is also a googleTalk available on youtube. From what I can remember, most browsers deal with string concatenations efficiently when number of elements is below few thousand. After that IE slows down at exponential rate, when firefox, chrome and safari are doing much better. This may change since IE9 isn't that far away now.

vikp