Possible Duplicate:
JavaScript string concatenation
does javascript have a built in stringbuilder class?
As it's known when we do str = str + "123"
a new string is created. If we have a large number of concatenations it can be rather expensive. Is there a simple way to implement a StringBuilder in JavaScript?
You can push the parts into an array, and then join it:
var builder = []
builder.push( "some", "123" );
builder.push( "content" );
var str = builder.join("");
This SO question explains it in detail, see also this class
Traditional concatenation in JavaScript is optimal if the strings are static.
var foo = 'a' + 'b' + 'c' + 'd';
this is true in most browsers. string-concatenation
If the strings may be variable according to the program either method is equally efficient.
var foo = ""+Math.random() + Math.random() + Math.random() + Math.random();
var foo = [Math.random(), Math.random(), Math.random(), Math.random()].join('');
the differences are not too great between browsers, but the traditional way seems a little better string-random-concatenation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With