0

Possible Duplicate:
Why is string concatenation faster than array join?

Usually we need to generate html contents dynamically in Javascript. Two ways like below:

var s = "", a = [];
for (var i = 0, l = data.length; i < l; i++) {
  s += "<a href='#'>" + data[i].name + "</a>";
  a[i] = "<a href='#'>" + data[i].name + "</a>";
}
container.innerHTML = s; // or
container.innerHTML = a.join("");

Which way is better? Mainly foucus on performance, or the differences can be ignored.

Community
  • 1
  • 1
dencey
  • 1,041
  • 17
  • 25

3 Answers3

2

This answers your question: High-performance String Concatenation in JavaScript

Ivan
  • 34,531
  • 8
  • 55
  • 100
Blaster
  • 9,414
  • 1
  • 29
  • 25
2

The array method is better.

When you concatenate strings, you will be copying the entire previous string to a new string for each iteration. In the end you will have copied a lot more data than the size of the resulting string. For each additional iteration the amount of data that you have copied roughly doubles, so it will get really much really fast.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    This isn't really true in anything but older versions of IE, some good information in this answer http://stackoverflow.com/a/7299040/68818. Array.join seems much faster in chrome as well from my testing, but much slower in firefox. – Andrew Barrett Jun 26 '12 at 07:39
  • @AndrewBarrett: Yes, it seems that they have done some real work on the string concatenation in later browsers, perhaps because string concatenation has been misused so much. The string concatentation is still a bad approach, and it might not remain as optimised in future browsers. – Guffa Jun 26 '12 at 08:37
2

This is pretty far from clearcut, as a legacy from having to support IE6/7 I always thought that the array method was much faster, but that appears to really not be the case.

Here is a test using a small string 'a':

Here is a test using a large string (first paragraph of lorem ipsum):

In all modern browsers (I tested IE9/Chrome19/FF12) the concatenation is faster, and much faster when using the longer strings.

It is important to note though that in IE7, the array method is much faster, so if you have to support that (and I would think twice about supporting IE7 now), then you should likely be using the array method, as IE7 is so slow with string concatenation as to be ridiculous.

Actually, if you have to support IE7, I would just steer away from using any sort of heavy client side JS!

Andrew Barrett
  • 19,721
  • 4
  • 47
  • 52