【发布时间】:2013-10-15 13:39:20
【问题描述】:
以下代码说明了问题,改变读/写的顺序导致执行时间有很大差异(使用Chrome、Firefox和IE测试):
// read->write->read->write...
function clearSlow(divs){
Array.prototype.forEach.call(divs, function(div) {
contents.push(div.clientWidth);
div.style.width = "10px";
});
}
// read->read->...->write->write...
function clearFast(divs){
Array.prototype.forEach.call(divs, function(div) {
contents.push(div.clientWidth);
});
Array.prototype.forEach.call(divs, function(div) {
div.style.width = "10px";
});
}
这是完整示例的 JSFiddle http://jsfiddle.net/Dq3KZ/2/。
我的 n=100 的结果:
慢速版本:~35ms
快速版本:~2ms
对于 n=1000:
慢速版:~2000ms
快速版本:~25ms
我认为这与每种情况下的浏览器重排次数有关。在慢速场景中,每次写入操作都会发生回流。但是,在快速方案中,回流仅在最后发生一次。但我不确定,也不明白为什么它会那样工作(当操作是独立的时)。
编辑:我使用 InnerText 属性而不是 clientWidth 和 Style.Width ,我在使用 Google Chrome (http://jsfiddle.net/pindexis/CW2BF/7/) 时得到了相同的行为。但是,当使用InnerHTML 时,几乎没有区别(http://jsfiddle.net/pindexis/8E5Yj/)。
Edit2:我已经为感兴趣的人开启了关于 innerHTML/innerText 问题的讨论:why does replacing InnerHTML with innerText causes >15X drop in performance
【问题讨论】:
标签: javascript performance google-chrome firefox dom