Dónal
Dónal

Reputation: 187529

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

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?

Upvotes: 91

Views: 203250

Answers (13)

Ed Kern
Ed Kern

Reputation: 151

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...

Upvotes: 4

James McMahon
James McMahon

Reputation: 49639

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.

Upvotes: 3

Eric Schoonover
Eric Schoonover

Reputation: 48402

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

Upvotes: 103

jasonc65
jasonc65

Reputation: 51

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.

Upvotes: 2

pcorcoran
pcorcoran

Reputation: 8082

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.

Upvotes: 46

Quentin
Quentin

Reputation: 943561

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).

Upvotes: 8

amix
amix

Reputation: 89

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("");

Upvotes: 8

William Keller
William Keller

Reputation: 5410

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.

Upvotes: 6

David Ameller
David Ameller

Reputation: 1814

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.

Upvotes: 1

Frank Krueger
Frank Krueger

Reputation: 70993

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(""));

Upvotes: 33

Bite code
Bite code

Reputation: 596753

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.

Upvotes: 0

Rahul
Rahul

Reputation: 12231

Try this:

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

Upvotes: 18

Michael Haren
Michael Haren

Reputation: 108256

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.

Upvotes: 37

Related Questions