is the + operator less performant than StringBuffer.append()

Dónal picture Dónal · Sep 21, 2008 · Viewed 196.6k times · Source

On my team, we usually do string concatentation like this:

var url = // some dynamically generated URL
var sb = new StringBuffer();
sb.append("<a href='").append(url).append("'>click here</a>");

Obviously the following is much more readable:

var url = // some dynamically generated URL
var sb = "<a href='" + url + "'>click here</a>";

But the JS experts claim that the + operator is less performant than StringBuffer.append(). Is this really true?

Answer

Eric Schoonover picture Eric Schoonover · Sep 21, 2008

Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.

Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis

join() once, concat() once, join() for, += for, concat() for

More:
Ajaxian >> String Performance in IE: Array.join vs += continued