3

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?

Community
  • 1
  • 1
Eugeny89
  • 3,797
  • 7
  • 51
  • 98

3 Answers3

10

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

Community
  • 1
  • 1
fiz
  • 564
  • 3
  • 12
  • I prefer the more concise notation: `var str = ['some', '123', 'content'].join('');` (usually with line breaks between items) – keithjgrant Jan 10 '13 at 14:37
1

I think, it's never really simple to implement a StringBuilder that is faster than normal string concatenations. And that's obviously the reason for the Builder.

Fill an array an if it's full convert it to string.

algorhythm
  • 8,530
  • 3
  • 35
  • 47
1

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

Scipion
  • 1,350
  • 1
  • 10
  • 16