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

JavascriptStringConcatenation

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.

If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.

Solution 3 - Javascript

Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks.

I would guess that string concatenation isn't going to be your bottleneck.

Solution 4 - Javascript

Agreed with Michael Haren.

Also consider the use of arrays and join if performance is indeed an issue.

var buffer = ["<a href='", url, "'>click here</a>"];
buffer.push("More stuff");
alert(buffer.join(""));

Solution 5 - Javascript

Try this:

var s = ["<a href='", url, "'>click here</a>"].join("");

Solution 6 - Javascript

JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).

I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).

Solution 7 - Javascript

Like already some users have noted: This is irrelevant for small strings.

And new JavaScript engines in Firefox, Safari or Google Chrome optimize so

"<a href='" + url + "'>click here</a>";

is as fast as

["<a href='", url, "'>click here</a>"].join("");

Solution 8 - Javascript

In the words of Knuth, "premature optimization is the root of all evil!" The small defference either way will most likely not have much of an effect in the end; I'd choose the more readable one.

Solution 9 - Javascript

The easier to read method saves humans perceptible amounts of time when looking at the code, whereas the "faster" method only wastes imperceptible and likely negligible amounts of time when people are browsing the page.

I know this post is lame, but I accidentally posted something entirely different thinking this was a different thread and I don't know how to delete posts. My bad...

Solution 10 - Javascript

It is pretty easy to set up a quick benchmark and check out Javascript performance variations using jspref.com. Which probably wasn't around when this question was asked. But for people stumbling on this question they should take alook at the site.

I did a quick test of various methods of concatenation at http://jsperf.com/string-concat-methods-test.

Solution 11 - Javascript

I like to use functional style, such as:

function href(url,txt) {
  return "<a href='" +url+ "'>" +txt+ "</a>"
}

function li(txt) {
  return "<li>" +txt+ "</li>"
}

function ul(arr) {
  return "<ul>" + arr.map(li).join("") + "</ul>"
}

document.write(
  ul(
    [
      href("http://url1","link1"),
      href("http://url2","link2"),
      href("http://url3","link3")
    ]
  )
)

This style looks readable and transparent. It leads to the creation of utilities which reduces repetition in code.

This also tends to use intermediate strings automatically.

Solution 12 - Javascript

As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.

Solution 13 - Javascript

Yes, according to the usual benchmarks. E.G : http://mckoss.com/jscript/SpeedTrial.htm.

But for the small strings, this is irrelevant. You will only care about performances on very large strings. What's more, in most JS script, the bottle neck is rarely on the string manipulations since there is not enough of it.

You'd better watch the DOM manipulation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionD&#243;nalView Question on Stackoverflow
Solution 1 - JavascriptEric SchoonoverView Answer on Stackoverflow
Solution 2 - JavascriptpcorcoranView Answer on Stackoverflow
Solution 3 - JavascriptMichael HarenView Answer on Stackoverflow
Solution 4 - JavascriptFrank KruegerView Answer on Stackoverflow
Solution 5 - JavascriptRahulView Answer on Stackoverflow
Solution 6 - JavascriptQuentinView Answer on Stackoverflow
Solution 7 - JavascriptamixView Answer on Stackoverflow
Solution 8 - JavascriptWilliam KellerView Answer on Stackoverflow
Solution 9 - JavascriptEd KernView Answer on Stackoverflow
Solution 10 - JavascriptJames McMahonView Answer on Stackoverflow
Solution 11 - Javascriptjasonc65View Answer on Stackoverflow
Solution 12 - JavascriptDavid AmellerView Answer on Stackoverflow
Solution 13 - Javascripte-satisView Answer on Stackoverflow