Tuesday, 12 December 2006

Joining strings

We've all been there before - concatenating strings of html, but which way is quicker?

1) Recursive concatenation.
var html = "<html>" + "<head>" + "<title>";

2) Append to the variable.
var html = "<html>";
html += "<head>";
html += "<title>";

3) Join the array
var html = ["<html>", "<head>", "<title>"].join("");

Smart engines such as SpiderMonkey (the basis for Netscape's original JavaScript engine - leading to Netscape, Firefox, etc) would use exactly the same underlying code for examples 1 and 2 - no speed difference at all. JScript in example 2 however would look up the html variable each time and use an intermediary to store the new values before discarding the old ones. So there would be a speed differential in JScript where example 1 is quicker than example 2.

The fastest string concatenation is using option 3 - this is down to the array's internal string builder facility which allows for much faster string manipulation. Of course it's only going to make a big difference when contactenating strings over many iterations - such as creating a large html table. Over a very small number of iterations the difference is so negligable as to be inconsequential.