Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How inefficient is String concatenation in Javascript?

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

like image 345
bobber205 Avatar asked Sep 23 '10 18:09

bobber205


1 Answers

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.

like image 161
bobince Avatar answered Oct 05 '22 12:10

bobince