为什么用innerText替换InnerHTML导致性能下降> 15X

Ami*_*sef 9 html javascript dom google-chrome

这个问题来自我之前的帖子,为什么DOM读/写操作的微小重新排序会导致巨大的性能差异.

考虑以下代码:

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 = "";
    });
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/pindexis/ZZrYK/

我的测试结果为n = 100:
ClearHTML:~1ms
ClearText:~15ms

对于n = 1000:
ClearHTML:~4ms
ClearText:~1000ms

我在google chrome和IE上测试了代码并得到了类似的结果(Firefox不支持innerText).

编辑: 两个函数之间的差异不是由于innerHTxt函数与innerHTML相比的缓慢造成的,这是肯定的(我尝试删除div.innerHTML =""并获得性能提升),这里发生了奇怪的浏览器重排.

Exp*_*lls 16

由于MDN解释说:

由于innerText知道CSS样式,它将触发重排,而textContent不会.

使用textContent而不是innerText不会导致回流,也很快.IE9 +也像FFX/Chrome一样支持它.