Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does replacing InnerHTML with innerText causes >15X drop in performance

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.

like image 676
Amine Hajyoussef Avatar asked Oct 08 '13 19:10

Amine Hajyoussef


2 Answers

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.

like image 187
Explosion Pills Avatar answered Oct 28 '22 23:10

Explosion Pills


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.

like image 35
riwalk Avatar answered Oct 29 '22 00:10

riwalk