Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to implement a StringBuilder in JavaScript [duplicate]

Tags:

javascript

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?

like image 869
Eugeny89 Avatar asked Sep 17 '25 10:09

Eugeny89


2 Answers

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

like image 151
fiz Avatar answered Sep 18 '25 22:09

fiz


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

like image 23
Scipion Avatar answered Sep 18 '25 22:09

Scipion