开发者

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 str开发者_运维问答ucture?

Thanks! :)


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.


Huge performance boost can be obtained by simply using intermediate strings! It is possible to create StringBuffer-like class in JavaScript to gain even more performance boost.

See the complete article and graphs here.


Efficiency of string concatenation will depend on a browser you are using. You can google for statistics, there is also a googleTalk available on youtube. From what I can remember, most browsers deal with string concatenations efficiently when number of elements is below few thousand. After that IE slows down at exponential rate, when firefox, chrome and safari are doing much better. This may change since IE9 isn't that far away now.


I once read an article about this subject which offerer some code to build buffered strings with arrays:

http://www.softwaresecretweapons.com/jspwiki/javascriptstringconcatenation

I tested it myself and it was way faster in IE... and way slower in Firefox!

To sum up: there're many JavaScript engines out there and we can't really rely on this sort of implementation details. If it's ever an issue, you'll notice. Before that, don't care too much.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜