4

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?

3
  • strings are immutable is JS, what do you mean by string builder ? like in C# ? Commented Jan 10, 2013 at 14:08
  • There's a post stackoverflow.com/questions/112158/… about string catenation techniques. Commented Jan 10, 2013 at 14:10
  • @camus, yes I'm thinking of StringBuilder like in C# Commented Jan 10, 2013 at 14:11

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I prefer the more concise notation: var str = ['some', '123', 'content'].join(''); (usually with line breaks between items)
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.