When innerHTML isn’t Fast Enough

This post isn't about the pros and cons of innerHTML vs. W3C DOM methods. That has been hashed and rehashed elsewhere. Instead, I'll show how you can combine the use of innerHTML and DOM methods to make your code potentially hundreds of times faster than innerHTML on its own, when working with large numbers of elements.

In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs. creating new ones. Knowing this, we can combine the speed of destroying elements by removing their parent using the standard DOM methods with creating new elements using innerHTML. (This technique is something I discovered during the development of RegexPal, and is one of its two main performance optimizations. The other is one-shot markup generation for match highlighting, which avoids needing to loop over matches or reference them individually.)

The code:

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

You can use the above as el = replaceHtml(el, newHtml) instead of el.innerHTML = newHtml.

innerHTML is already pretty fast...is this really warranted?

That depends on how many elements you're overwriting. In RegexPal, every keydown event potentially triggers the destruction and creation of thousands of elements (in order to make the syntax and match highlighting work). In such cases, the above approach has enormous positive impact. Even something as simple as el.innerHTML += str or el.innerHTML = "" could be a performance disaster if the element you're updating happens to have a few thousand children.

I've created a page which allows you to easily test the performance difference of innerHTML and my replaceHtml function with various numbers of elements. Make sure to try it out in a few browsers for comparison. Following are a couple examples of typical results from Firefox 2.0.0.6 on my system:

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)

I think the numbers speak for themselves. Comparable performance improvements can also be seen in Safari. In Opera, replaceHtml is still typically faster than innerHTML, but by a narrower margin. In IE, simple use of innerHTML is typically faster than mixing it with DOM methods, but not by nearly the same kinds of margins as you can see above. Nevertheless, IE's conditional compilation feature is used to avoid the relatively minor performance penalty, by just using innerHTML with that browser.

83 thoughts on “When innerHTML isn’t Fast Enough”

  1. fn=function (){……}
    el.addEventListener(‘click’,fn , false);
    replaceHtml(el,html);

    when click on e1,fn can’t work,
    fix it

  2. Hi, wont be another a**hole that tells you your code sucks and my approach is better than yours.

    I just like to thank you for sharing such a great code! This is so cool!!!!Yebah!

  3. BTW, i visited “The Big Dumb Developer” and tested his workaround and found out how sucky the solution was that was supposed to, as said to be-“better.” I’d say F*** off dude! again, Kudos for this post! (:

  4. em… how about enclose the new HTML message with another node, then assign to innerHTML?
    i.g.
    node.innerHTML = +message+ ?
    This may reduce the time FF need to clean up the things?

  5. Tried this today as an attempt to improve FireFox innerHTML performance on a page that takes over a minute to load (versus only 20 seconds in Safari), but no joy. Performance of replaceChild was identical to innerHTML (or at least within the ~1 second margin of error) in both Safari 4.0.5 and FF 3.6. Maybe it’s still useful for older browsers, but I sure do with FireFox’s innerHTML performance wasn’t so awful.

    Apparently the best I can do is disable incremental loading/display in FireFox. *sigh* If anybody has any better suggestions (that don’t involve chunking and parsing the HTML in JavaScript), I’d love to hear them.

  6. Err.. I sure do wish FF’s innerHTML performance weren’t so awful. Gotta watch the typos.

  7. I spoke too soon. My code was getting bounded by FireFox’s awful string length performance on the XMLHttpRequest’s contentText. That performance hit so completely overshadowed the innerHTML performance that I have no idea whether this helped or not…. *grrrr*

  8. Great!!
    I was just in this sort of trouble, your code improved the speed of my website significantly and saved my ass!!
    Thank you!!

  9. Thanks! It really speed up loading on firefox while using dhtml on big object.

    Very good job!

    Beer for you! ^^

  10. I noticed no performance improvements over a series of HUGE html inserts. Apparently it became like 1% slower with this – but at least I could isolate the HTML changing part of my code to profile on Firebug ๐Ÿ™‚

  11. By the way, this would be *even faster* if you simply assign the function once based on the conditional compilation being present or not, like so:

    // for everybody except IE
    function replaceHtml(el, html) {
    var oldEl = typeof el === “string” ? document.getElementById(el) : el;
    var newEl = oldEl.cloneNode(false);
    newEl.innerHTML = html;
    oldEl.parentNode.replaceChild(newEl, oldEl);
    /* Since we just removed the old element from the DOM, return a reference
    to the new element, which can be used to restore variable references. */
    return newEl;
    };

    // Pure innerHTML is slightly faster in IE, so change the function
    /*@cc_on
    function replaceHtml(el, html) {
    var oldEl = typeof el === “string” ? document.getElementById(el) : el;
    oldEl.innerHTML = html;
    return oldEl;
    }
    @*/

    https://gist.github.com/887592 (in case my text is messed up)

  12. Replacing the element may cause some problems since existing javascript objects may refer to the replaced object. This will cause two kind of problems because the old and new elements will be referenced: 1) incoherence 2) memory leak.

    I prefer “The Big Dump Developer” solution which avoids the incoherence and memory leak.

  13. Doesn’t seem to have any effect on Firefox anymore, but it still has huge speed boosts in Chrome 18. I was using innerHTML to push a very large table (500+ rows, 15 columns). It went from 70ms to 40ms using the replaceHTML function.

  14. Absolutely awesome. Been needing this solution for a long time. Bravo. The performance gain is so great.

  15. I ran all the tests in Chrome. They are the same for both. For fewer elements, the innerHTML is faster sometimes by 1-2 ms, for 10k and 14k, replaceHTML is faster by 3-4 ms.

    Also, good to see how browsers improved in 7 years. My results for 15K in Chrome:

    15000 elements…
    innerHTML (destroy only): 34ms
    innerHTML (create only): 18ms
    innerHTML (destroy & create): 55ms
    replaceHtml (destroy only): 34ms (~ same speed)
    replaceHtml (create only): 18ms (~ same speed)
    replaceHtml (destroy & create): 51ms (~ same speed)
    Done.

  16. I would like to make updated tests on your function… but your link is broken. Could you share it again? Thanks =D

Leave a Reply

Your email address will not be published. Required fields are marked *