为什么用innerText替换InnerHTML会导致性能下降15%
这个问题源于我之前发布的为什么对DOM读/写操作的微小重新排序会导致巨大的性能差异。
this question arises from my previous post why a tiny reordering of DOM Read/Write operations causes a huge performance difference .
考虑以下代码:
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/
我的测试结果为n = 100:
清除HTML:〜1ms
ClearText:〜15ms
My test results for n=100:
ClearHTML: ~1ms
ClearText: ~15ms
n = 1000:
清除HTML:〜4ms
ClearText:〜1000ms
for n=1000:
ClearHTML: ~4ms
ClearText: ~1000ms
我测试了google chrome和IE上的代码,并得到类似的结果(Firefox不支持innerText)。
I tested the code on google chrome and IE and get similar results (Firefox does not support innerText).
编辑:
这两个函数之间的区别并不是因为innerText函数与innerHTML相比较慢,这是肯定的(我尝试删除 div.innerHTML =
并提升性能),这里有奇怪的浏览器回流。
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.
如 MDN解释:
As MDN explains:
由于innerText意识到CSS样式,它将触发回流,而textContent不会。
As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
使用 textContent
而不是 innerText
不引起回流并且速度也快。 IE9 +也支持它与FFX / Chrome一样。
Using textContent
instead of innerText
does not cause reflow and is also fast. IE9+ also supports it as does FFX/Chrome.