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:
for(x=0;x<5000;x++)
  html +
'Lorem ipsum dolor sit amet, consectetuer bla bla <br />';
var 
= 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("");
    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("");}
I ran the test again using my new class like:
var html = new StringBuilder("");
for
(x=0;x<5000;x++)
  html.append(
'Lorem ipsum dolor sit amet, consectetuer bla bla <br />');
var 
= 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...

0 Comments:

Post a Comment

<< Home