I have a vanilla JavaScript function to test appending large numbers of elements to the DOM:
var start = new Date().getTime();
var blah;
var div = document.getElementById("me");
for (i = 0; i < 5000; ++i) {
div.innerHTML += "<div>" + i + "</div>";//Simply add to div.
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
Chrome IE10
------ -----
Vanilla 39 130 (seconds)
for (i = 0; i < 5000; ++i) {
$("#me").append("<div>" + i + "</div>");//Now using append instead.
}
Chrome IE10
------ -----
Vanilla 39000 130,000 (milliseconds)
JQuery 260 1300 (milliseconds)
NB: It didn't seem to have any impact on performance if I used the $("#me")
selector or passed in $(div)
AppendChild
:for (i = 0; i < 5000; ++i) {
var el = document.createElement("div");//Now create an element and append it.
el.innerHTML = i;
div.appendChild(el);
}
Chrome IE10
------ -----
Vanilla 39000 130,000 (ms)
JQuery 260 1300 (ms)
AppendChild 30 240 (ms)
To my huge surprise this was by far the fastest, most performant. On Chrome it takes a whopping 30ms or so, and on IE it takes around 240ms.
You can play with all the variations here: Fiddle
I know there could be many other variations to test, but what is jQuery doing behind the scenes to make it's .append()
so much faster than native JS innerHTML +=
and why is creating a new element and appending it even faster?
If you do things right, you can pretty much double your "best" result.
Native DOM methods are always faster than their jQuery alternatives. However, .innerHTML
is not ideal.
When you use .innerHTML += ...
, here's what happens:
The native methods are significantly less work ;)
It should also be noted that innerHTML += ...
completely nukes the DOM, meaning any references to the old elements are lost and in particular event handlers are not kept (unless you used inline event handlers, which you shouldn't be)
Behind the scenes, jQuery is using document fragments, which perform much better than straight manipulation of the document. John Resig discussed document fragments' superior performance in 2008, which should give you a solid explanation about what jQuery is doing and why.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With