It is very common for people who do C#/.NET to utilize the StringBuilder object/construct to construct strings rather than concatenation. If you don’t well….....
That image of Jean-Luc Picard/Sir Patrick Stewart says it all for me what I feel about people who use old school concatenation all the time.
The reason why this is done in .NET is because it joins collections faster than it does joining/concatenation of strings. There are lots of reasons for this that I won’t delve into as it deserves a series of blog posts on its own.
Now in JavaScript, that construct/object is not in place at all. That leaves us to write very fun concatenation stuff all over the place. Previously it was not much of a problem as I never had the need to write really fancy JavaScript code in the past. Well now I have, on a MS Word Task Pane no less which as you may have guessed, runs on IE.
Now IE has made quite a fair bit of strides in performance but it still lags behind a lot of other browsers. One of it apparently is string concatenation. I was experiencing some very interesting stutters when it was concatenating strings. It isn’t something that is a real deal breaker or causes the BSOD but it was irritating the perfectionist in me.
I deduced that something that worked in C# should help, if not solve that issue I had with JavaScript. I was right. The code I wrote is here:
function StringBuilder(value) {
this.strings = new Array();
this.append(value);
}
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
StringBuilder.prototype.clear = function () {
this.strings.length = 0;
}
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
var sb = new StringBuilder();
sb.append("This is");
sb.append("much better looking");
sb.append("than using +=");
// joins the string
var myString = sb.toString();
// Cleans out the string buffer in the StringBuilder.
// This effectively makes it empty in case you did not
// know what cleaning out a buffer in this context
// meant.
sb.clear();
I did some independent tests and discovered that it took a full 10 seconds to concatenate 10,000 strings while the code I wrote got it done in less than 1 second. The 10,000 strings bit was just me being curious. If your single page app is concatenating 10,000 strings, you have a problem and you need to rethink your architecture. I reiterate the 10,000 strings bit was just me being curious.
Anyway, I hope this code snipped helps tune up your JS code and also makes it more aesthetically pleasing.