为什么用innerText替换InnerHTML会导致性能下降15% [英] why does replacing InnerHTML with innerText causes >15X drop in performance

查看:151
本文介绍了为什么用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解释< a>:

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.

这篇关于为什么用innerText替换InnerHTML会导致性能下降15%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆