I’m trying to figure out the most performant way of deep-cloning a DOM tree within the browser.
If I start out with
var div = document.getElementById('source'); var markup = div.innerHTML;
What will be faster,
var target = div.cloneNode(true);
or
var target = document.cloneNode(false); target.innerHTML = markup;
I understand the browser platform may make a big difference here, so any information about how these compare in the real world would be appreciated.
Let’s test!
I added the following code to a copy of StackOverflow’s Questions page (removing existing scripts first, and running from scratch with one of the
timeit()s uncommented each time around, three runs of 100 ops:Here are the results running on a VirtualBox on a Core 2 Q9300:
So
cloneNode(true)is much faster than copyinginnerHTML. Of course, it was always going to be; serialising a DOM to text and then re-parsing it from HTML is hard work. The reason DOM child operations are usually slow is that you’re inserting/moving them one-by-one; all-at-once DOM operations likecloneNodedon’t have to do that.Safari manages to do the
innerHTMLop amazingly quickly, but still not nearly as quickly as it doescloneNode. IE is, as expected, a dog.So, auto -1s all round to everyone who said innerHTML would Obviously Be Faster without considering what the question was actually doing.
And yes, jQuery uses innerHTML to clone. Not because it’s faster though — read the source:
jQuery uses
Element.attachEvent()to implement its own event system, so naturally, it needs to avoid that bug. If you don’t need to, you can avoid the overhead.Off-topic aside: Then again, I think holding jQuery up as the pinnacle of Best Practice may be a bit mistaken, especially given the next line:
That’s right — jQuery adds its own arbitrary attributes to HTML elements and then needs to get rid of them when it clones them (or otherwise gives access to their markup, such as through the
$().html()method). This is ugly enough, but then it thinks the best way to do that is processing HTML using a regular expression, which is the kind of basic mistake you’d expect more from naïve 1-reputation SO questioners than the author of the Second Coming Best JS Framework Evar.Hope you didn’t have the string
jQuery1="2"anywhere in your text content, ‘cos if so you just mysteriously lost it. Thanks, jQuery! Thus ends the off-topic aside.