replaceHTML for when innerHTML dogs you down

Written by on September 13th, 2007 in Ajax News.

Steven Levithan, of RegexPal, ran into some performance issues with innerHTML due to the fact that “every keydown event potentially triggers the destruction and creation of thousands of elements” so he started to look into it.

He has a test page that demonstrates the issue. Here is some sample input:

1000 elements…
innerHTML (destroy only): 156ms
innerHTML (create only): 15ms
innerHTML (destroy & create): 172ms
replaceHtml (destroy only): 0ms (faster)
replaceHtml (create only): 15ms (~ same speed)
replaceHtml (destroy & create): 15ms (11.5x faster)

15000 elements…
innerHTML (destroy only): 14703ms
innerHTML (create only): 250ms
innerHTML (destroy & create): 14922ms
replaceHtml (destroy only): 31ms (474.3x faster)
replaceHtml (create only): 250ms (~ same speed)
replaceHtml (destroy & create): 297ms (50.2x faster)

The code for his replaceHTML is:

JAVASCRIPT:

  1.  
  2. /* This is much faster than using (el.innerHTML = str) when there are many
  3. existing descendants, because in some browsers, innerHTML spends much longer
  4. removing existing elements than it does creating new ones. */
  5. function replaceHtml(el, html) {
  6.         var oldEl = (typeof el === “string” ? document.getElementById(el) : el);
  7.         var newEl = document.createElement(oldEl.nodeName);
  8.         // Preserve the element’s id and class (other properties are lost)
  9.         newEl.id = oldEl.id;
  10.         newEl.className = oldEl.className;
  11.         // Replace the old with the new
  12.         newEl.innerHTML = html;
  13.         oldEl.parentNode.replaceChild(newEl, oldEl);
  14.         /* Since we just removed the old element from the DOM, return a reference
  15.         to the new element, which can be used to restore variable references. */
  16.         return newEl;
  17. };
  18.  

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/155928179/replacehtml-for-when-innerhtml-dogs-you-down

Leave a Reply

You must be logged in to post a comment.



Site Navigation