Introduction
Once upon a time, not so long ago, pushing any significant processing to the client browser was considered a bad practice. Now with the rise in popularity of AJAX style development, it has suddenly become a hot new technology. Unfortunately, the most commonly used browser on the market is painfully slow at one of the most common tasks in programming -- string concatenation.
The good news is that although IE is slow when it comes to string concatenation, it is quite fast with array operations. With this in mind, I decided to write a simple StringBuilder
class that pushes individual strings into an array and then uses the join method to produce the concatenated output string. In tests I have run with 5,000 strings, it is 117 times faster than the equivalent string concatenation using the s1 += s2 syntax. With 10,000 strings, it is an amazing 261 times faster!
Using the code
The StringBuilder
class only provides four methods: a constructor, an append
method, a clear
method, and a toString
method. You can add more properties and methods if you need them, but I chose to keep it as simple as possible for this article.
Here is the entire script that defines the StringBuilder
class:
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 = 1;
}
StringBuilder.prototype.toString = function ()
{
return this.strings.join("");
}
The code is so simple and straightforward that it should be self-explanatory. Now here's an example of how to use it:
var sb = new StringBuilder();
sb.append("Lorem ipsum dolor sit amet, consectetuer adipiscing elit, ");
sb.append("sed diem nonummy nibh euismod tincidunt ut lacreet dolore ");
sb.append("magna aliguam erat volutpat.");
var s = sb.toString();
Again, so simple and straightforward it shouldn't require any further explanation. If you've ever used the StringBuilder
in .NET, then you already know how to use this one.
If you download the demo project, you will find an HTML page that performs a side-by-side comparison of StringBuilder
vs. string concatenation. You can use it to run your own tests to see the difference for yourself. On my machine, it takes IE over 14 seconds to concatenate 5,000 strings. The StringBuilder
does it in 110 ms. With 10,000 strings, it takes IE a full minute to concatenate. The StringBuilder
does it in 230 ms. More than a minute to less than a quarter of a second, that's a fairly significant improvement!
Conclusion
The whole purpose of pushing processing to the client is to provide a richer, more responsive user experience. That means, it's important to make sure the client-side code is as efficient as possible. I hope this article helps your client-side string building code really scream.