this question arises from my previous post why a tiny reordering of DOM Read/Write operations causes a huge performance difference .
consider the following code:
function clearHTML(divs) {
Array.prototype.forEach.call(divs, function (div) {
contents.push(div.innerHTML);
div.innerHTML = "";
});
}
function clearText(divs) {
Array.prototype.forEach.call(divs, function (div) {
contents.push(div.innerText); //innerText in place of innerHTML
div.innerHTML = "";
});
}
http://jsfiddle.net/pindexis/ZZrYK/
My test results for n=100:
ClearHTML: ~1ms
ClearText: ~15ms
for n=1000:
ClearHTML: ~4ms
ClearText: ~1000ms
I tested the code on google chrome and IE and get similar results (Firefox does not support innerText).
Edit :
the difference between the two functions is not caused by the slowness of innerText function compared to innerHTML, that's for sure ( I tried removing div.innerHTML =""
and got boost in performance), there's strange browser reflow taking place here.
As MDN explains:
As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
Using textContent
instead of innerText
does not cause reflow and is also fast. IE9+ also supports it as does FFX/Chrome.
The difference almost certainly comes from the extra effort it takes to get the InnerText (which I believe removes extraneous tags and just returns the text within an element). InnerHTML on the other hand simply returns data that has already been parsed and understood by the browser.
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