Tuesday, April 9, 2013

Static HTML vs JavaScript dynamic generation - which is faster?

Say you have a page containing a huge amount of data - a list of 1000 customers or products. Such a list may take a long time to render. I always wondered if it's actually faster to render the page using a clever JavaScript loop instead of one big chunk of static HTML. So I did a small benchmark to determine which method renders faster.
Consider the following example. It's a simple HTML unordered list representing folders and files:
  • Folder 0
    • File 0
    • File 1
    • File 2
  • Folder 1
    • File 0
    • File 1
    • File 2
First, let's do it in plain old HTML:
<ul id="folderList">
 <li>Folder 0
  <ul>
   <li>File 0</li>
   <li>File 1</li>
   <li>File 2</li>
  </ul>
 </li>
 <li>Folder 1
  <ul>
   <li>File 0</li>
   <li>File 1</li>
   <li>File 2</li>
  </ul>
 </li>
</ul>
Now, let's generate the same output using JavaScript:
var h = [];

for(var i=0;i<=1;i++)
{
 h.push("<li>Folder ");
 h.push(i);
 h.push("<ul>");
 
 for(var k=0;k<=2;k++)
 {
  h.push("<li>File ");
  h.push(k);
  h.push("</li>");
 }
 
 h.push("</ul></li>");
}

document.getElementById("folderList").innerHTML = h.join("");
You may think this script looks ugly, but it's actually the fastest way to manipulate the DOM in JavaScript. You create an array of strings and add chunks of HTML to it. Then you join (or concatenate) the array to form one big string and set the parent element's innerHTML property to it.
To evaluate both methods, I created two HTML files, both containing a huge list of 500 folders x 500 files (250.000 items in total). The first file is using static HTML and the second file is using a JavaScript loop to generate the items dynamically. For the record, the static HTML file had an impressive size of 16 MB.
I then loaded each page locally with Firefox and used the YSlow add-on to measure page loading time. If you want to test this for yourself, I uploaded both the plain HTML and the JavaScript benchmark page.
The result (lower is better):
  • Plain HTML: 17 seconds
  • JavaScript: 9 seconds
Quite surprising, I wouldn't have thought that. JavaScript generation is about two times faster! Keep in mind this goes only for the optimized JavaScript method I used above. If you use something more sophisticated like a JavaScript template engine, this performance advantage will certainly fade, as these template engines are about 5-10 times slower compared to the string array method. They could be even slower than using static HTML, but I haven't tested that.
A downside of the string array method is that it produces ugly code, with a template engine you'll have a much prettier syntax. Another downside with JavaScript templating is that it complicates machine readability. For example, automated parsers like search engines or screen readers may have problems with it. Only use script generated data for non-SEO relevant content.

No comments:

Post a Comment