Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 89522  / 11 Years ago, fri, august 23, 2013, 12:00:00

This site's run a test between the 3 different methods and it seems .html is the fastest, followed by .append. followed by .innerHTML. Can someone explain to me the reasons why?



Here's the site which does the comparison among the three methods.



I have read this this SO question which is related but I don't really understand the given answer, and the question didn't really elaborate much regarding .innerHtml.



I don't understand the following part:




A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div').




Can someone simplify this?


More From » jquery

 Answers
56

That benchmark is worthless. innerHTML is always faster than DOM manipulation.


jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can.


jQuery from benchmark


var html = '';
for (var i = 0; i < len; i++) {
html += '<div>Test ' + i + '</div>';
}

$('#list').html(html);

innerHTML from benchmark


var list = document.getElementById('list');
for (var i = 0; i < len; i++) {
list.innerHTML = list.innerHTML + '<div>Test ' + i + '</div>';
}



The test for innerHTML would be a lot faster if it was written like:


var list = document.getElementById('list');
var html = '';

for (var i = 0; i < len; i++) {
html += '<div>Test ' + i + '</div>';
}

list.innerHTML = html;

http://jsben.ch/#/yDvKH


[#76197] Thursday, August 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevenjeffreyr

Total Points: 286
Total Questions: 112
Total Answers: 95

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;