Archive

Posts Tagged ‘Javascript’

Javascript performance – writing to innerHTML

Recently I was investigating why the performance of one of my AJAX experiment is so bad.

This page uses a Perl CGI script to query a handful of deals sites for syndication of their deals and puts them together in one big RSS. Then the Javascript part displays the big collection of deals as a list. The list can be then narrowed down based on keywords as they are typed.

Since the big RSS usually contains more than 300 entries, the Javascript that was converting the entries into list items in an unordered list, was taking upto 10-15 seconds to render. This was not very pleasant.

Here’s how that part of the code looked:

  for ( it = 0; it < items.length; it++) {
    var item = items[it];
    var it_title = item.getElementsByTagName('title').item(0).firstChild.data;
    var it_link  = item.getElementsByTagName('link').item(0).firstChild.data;

    this.port.innerHTML += "<li class=" + it_li_class + "><a href=\\""
                           + it_link + "\\" target=\\"feedr_win\\">"
                           + it_title + "</a>";
  }

After a few experiments, I found that the assignment to this.port.innerHTML was the one that was most expensive. I modified the code to read:

  var html_str = "";

  for ( it = 0; it < items.length; it++) {
    var item = items[it];
    var it_title = item.getElementsByTagName('title').item(0).firstChild.data;
    var it_link  = item.getElementsByTagName('link').item(0).firstChild.data;

    html_str += "<li class=" + it_li_class + "><a href=\\""
             + it_link + "\\" target=\\"feedr_win\\">"
             + it_title + "</a>";
  }

  this.port.innerHTML = html_str;

That cut the time to less than a second. More than a 10x-15x performance improvement.

Next time I write something directly into innerHTML from Javascript in a loop, I am going to try and see if I can collect the text first and then write it into innerHTML.

Tags: ,