JavaScript String Concatenation

Having just read this article about JavaScript performance issues, I decided to try my own little experiment to see whether I got the same results. Unfortunately, I did not.

The article advocates using the join() method on a JavaScript array of strings over using plain old += as a way to speed up string concatenation operations.

The suthor says that his technique yields a 2484%(!) increase in speed in IE and that Firefox executes both methods in roughly the same amount of time. As a Dashboard widget developer, I of course went straight to Safari and Dashboard to try this out. Now, it may be because I’m running the beta of Safari 3 (though in general I’ve found it to be very fast), but in my limited testing, Safari actually performed about 50% worse using the Array.join method method. What was really surprising, though, was that in a Dashboard widget, the Array.join method performed 3 times worse than plain old string concatenation. What’s up with that?

Specifically, running the function below (on my 2.0GHz Core 2 duo MacBook with 2GB of RAM), the times I saw were as follows (averages are over 5 test runs):

Safari 3 beta (build 522.12)
Method Avg Time High Low
+= 141 ms 154 ms 98 ms
Array.join() 220 ms 225 ms 216 ms
Mac OS X Dashboard
Method Avg Time High Low
+= 252 ms 256 ms 250 ms
Array.join() 820 ms 856 ms 804 ms

Here’s the function:

function runTest() {
  var iters = 100000;
  var timer = {
    start: undefined,
    end: undefined
  };
  timer.start = (new Date()).getTime();
  var str = '';
  for (var i = 0; i < iters; ++i) {
    str += 'Rastafarian ';
  }
  timer.end = (new Date()).getTime();
  document.getElementById('plusequals').value = (timer.end - timer.start);
  timer.start = (new Date()).getTime();
  var buf = [];
  for (var i = 0; i < iters; ++i) {
    buf[i] = 'Rastafarian ';
  }
  var str = buf.join('');
  timer.end = (new Date()).getTime();
  document.getElementById('join').value = (timer.end - timer.start);
}

+=
join()

Was this page useful to you? Loading...