这个问题来自我之前的帖子,为什么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 =""并获得性能提升),这里发生了奇怪的浏览器重排.