91

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?

Dónal
  • 185,044
  • 174
  • 569
  • 824
  • 98
    There is no StringBuffer in javascript – Tomas May 12 '10 at 11:43
  • 7
    Don, were you referring to Java? – James McMahon Jul 14 '10 at 15:24
  • My experience was that `[].join('')` has shown some really wired behaviour, so i fel back to + :-/ – martyglaubitz Mar 19 '12 at 00:27
  • 1
    I know the fundamental question here is about string concatenation but you should use caution when creating html elements like this. Your example could break if the `url` contains `'` or `\n`. – styfle Jul 24 '13 at 20:24
  • Possible duplicate of [Most efficient way to concatenate strings in JavaScript?](https://stackoverflow.com/questions/16696632/most-efficient-way-to-concatenate-strings-in-javascript) – Ciro Santilli OurBigBook.com Oct 12 '19 at 22:57
  • 1
    I wonder why this question was not closed for lacking clarity. Instead it has 91 upvotes. There is no StringBuffer in JS so how is this even a valid question? – Omkar76 Oct 28 '20 at 11:31
  • This question is unclear (as others have noted) and is also a duplicate https://stackoverflow.com/questions/16696632/most-efficient-way-to-concatenate-strings-in-javascript – Inigo Apr 06 '21 at 11:40

13 Answers13

102

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

Jeremy
  • 1
  • 85
  • 340
  • 366
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
  • 10
    Regarding the graph, in case it's not obvious; lower is better. – Teekin Sep 15 '10 at 20:37
  • 1
    "First things first with the performance improvements with IE7, we no longer need to consider using an alternate path when doing large scale string operations; using Array.join in an iterative situation gives you no major advantages than using += in the same situation. In addition, the differences with IE6 were slight enough to allow you to not bother forking for that specific version." – Chris S Jan 11 '11 at 11:08
  • 2
    @Chris, that's not true. Compare these two fiddles in **IE7**: http://jsfiddle.net/9uS4n/5/ (fast) vs. http://jsfiddle.net/9uS4n/2/ (slow). There appears to be at least a 1000 times improvement in performance using the `join()` technique. – Kirk Woll Jul 22 '11 at 17:57
  • Nice explanation. Please also review this: http://www.iliadraznin.com/2012/03/string-concatenation-array-join-performance-javascript/#comment-938 – will824 Jul 23 '13 at 21:12
46

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.

user710437
  • 55
  • 1
  • 1
  • 5
pcorcoran
  • 7,894
  • 6
  • 28
  • 26
37

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.

Michael Haren
  • 105,752
  • 40
  • 168
  • 205
33

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(""));
Community
  • 1
  • 1
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
  • 3
    I know that a correct answer has been selected, but this answer has a more useful example. – Jason Sperske Apr 07 '10 at 16:41
  • 1
    Wow, just wow. Compare these two fiddles in **IE7**: http://jsfiddle.net/9uS4n/5/ (fast) vs. http://jsfiddle.net/9uS4n/2/ (slow). There appears to be at least a 1000 times improvement in performance using this technique. – Kirk Woll Jul 22 '11 at 17:54
  • @KirkWoll: Might want to use [jsPerf](http://jsperf.com/) in the future so we can easily compare results. – rvighne Aug 17 '14 at 19:15
  • i've been doing this lately too, similar code style to a .NET StringBuilder, var sb = []; sb.push("section 1"); sb.push("section 2"); return sb.join(''); – Sam Jones Dec 29 '14 at 14:22
  • This jsPerf https://jsperf.com/join-concat/2 mentioned at: https://stackoverflow.com/questions/16696632/most-efficient-way-to-concatenate-strings-in-javascript/16696775#16696775 seems to indicate that `+=` is faster. – Ciro Santilli OurBigBook.com Oct 12 '19 at 22:55
18

Try this:

var s = ["<a href='", url, "'>click here</a>"].join("");
Rahul
  • 12,181
  • 5
  • 43
  • 64
  • Well, the post you linked to in your answer specifically tries to disprove the "myth" of Array.join which my answer suggests. So perhaps not. I merely posted what I've seen to be faster in practice. – Rahul Sep 21 '08 at 21:49
  • love this method of string concat. – bkwdesign Mar 11 '14 at 17:47
8

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
8

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("");
amix
  • 89
  • 1
  • 3
6

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.

William Keller
  • 5,256
  • 1
  • 25
  • 22
  • 1
    Traditionally StringBuffer is used over concatenation because the former has O(N) time complexity whereas the latter as O(N^2), thus the difference is significant for large N (but not for small N). In any case the O(N^2) scenario may not be the case in JavaScript depending on the environment in use. – redcalx Aug 30 '11 at 11:20
4

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

Ed Kern
  • 151
  • 1
  • 3
3

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.

James McMahon
  • 48,506
  • 64
  • 207
  • 283
  • Judging by that it looks like nowadays that concatenation with the + operator is definitely the way to go. Unless I'm reading it wrong. Which is entirely plausible. – Richard Nov 28 '13 at 11:24
2

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.

jasonc65
  • 51
  • 4
1

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.

David Ameller
  • 1,774
  • 3
  • 18
  • 25
  • This isn't actually bad advice, I don't know why it's voted down so much. I know it doesn't answer the specific question, but it deserves recognition as being generally good advice. – eyelidlessness Apr 24 '10 at 06:33
0

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.

Bite code
  • 578,959
  • 113
  • 301
  • 329
  • Link is dead.. [https://web.archive.org/web/20150912072015/http://mckoss.com/jscript/SpeedTrial.htm](https://web.archive.org/web/20150912072015/http://mckoss.com/jscript/SpeedTrial.htm) points to the web archive version. – Tony Jul 27 '18 at 10:26