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! :)
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! :)
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.
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.
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.