I Need A Dip

Friday, April 07, 2006

JavaScript StringBuilder

The big web project that I have been working on lately utilizes a ton AJAX. Specificaly AjaxPro.NET.

As a result I have been doing a ton more JavaScript developement and client side rendering of tables and what not (string concatenation).
I noticed that creating HTML on the client wasn't as fast as I would like when constructing large tables to be displayed so I did a couple of tests.

First I just looped through 5,000 times creating a very large string like:
  html +
'Lorem ipsum dolor sit amet, consectetuer bla bla <br />';
= document.getElementById("results");
s.innerHTML html;
This took about 2.8 seconds in IE. (on average)

Next I created the following string builder class:
function StringBuilder(value){
this.strings = new Array("");
= function (value){
if (value)this.strings.push(value);
= function (){this.strings.length 1;}
= function (){return this.strings.join("");}
I ran the test again using my new class like:
var html = new StringBuilder("");
'Lorem ipsum dolor sit amet, consectetuer bla bla <br />');
= document.getElementById("results");
s.innerHTML html.toString();
The average results using the string builder was about 62 milliseconds.
While the results weren't as drastic in FireFox, the StringBuilder class was 2 to 3 times faster.

Give it a try...