我正在测试将 html 元素动态添加到 DOM 的不同方法的速度。我构建了一个测试器 here (代码是工作版本,非常草率)。对于不同的浏览器,结果(非常)不同,Chrome 在速度方面获得了所有分数,而 Opera 位居第二 - 但这不是这里的问题。
在 Firefox 中,我检测到清除 div(从它的子节点)时出现问题。添加大约 50.000 个 div 元素时,需要很长时间才能清除,仅使用
[div].innerHTML = "";
这是怎么回事? Firefox 是否为此实现了一些内在的垃圾收集方法?
最佳答案
虽然我不确定 innerHTML = "",但您遗漏了一个可能使用 DocumentFragments 插入到 DOM 中的快速方法:As John Resig shows .
正如 Ólafur Waage 已经提到的,尽管 innerHTML 在很多情况下速度更快,因为它不是任何 W3C 的一部分。标准,怪癖被引入的可能性要大得多。更不用说 innerHTML 不是现代浏览器中的事实标准。
This blog post似乎表明 Firefox 在使用 innerHTML 删除元素时会花费大量时间自行清理。
In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs. creating new ones. Knowing this, we can combine the speed of destroying elements by removing their parent using the standard DOM methods with creating new elements using innerHTML.
关于javascript - 为什么 innerHTML = ""在 Firefox 中很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/609698/