原文来自 replaceHTML for when innerHTML dogs you down
这个叫 ven Levithan 的家伙做了测试发现:innnerHTML 在清除(清空已有的 html 代码)的时候花费的时间最多,于是写了个创建+替换的方法,这样速度快,尤其是页面元素很多的情况下。
/* This is much faster than using (el.innerHTML = str) when there are many
existing descendants, because in some browsers, innerHTML spends much longer
removing existing elements than it does creating new ones. */
function replaceHtml(el, html) {
var oldEl = (typeof el === “string” ? document.getElementById(el) : el);
var newEl = document.createElement(oldEl.nodeName);
// Preserve the element’s id and class (other properties are lost)
newEl.id = oldEl.id;
newEl.className = oldEl.className;
// Replace the old with the new
newEl.innerHTML = html;
oldEl.parentNode.replaceChild(newEl, oldEl);
/* Since we just removed the old element from the DOM, return a reference
to the new element, which can be used to restore variable references. */
return newEl;
};
意义不是特别大,但钻研精神值得敬佩。根据留言看来,似乎 firefox 在这个问题上(destroy html)的效率最低。IE 用 replaceHTML 处理15000 个元素的时候,性能反而有所下降。
FF2
15000 elements…
innerHTML (destroy only): 26687ms
innerHTML (create only): 656ms
innerHTML (destroy & create): 27969ms
replaceHtml (destroy only): 110ms (242.6x faster)
replaceHtml (create only): 594ms (1.1x faster)
replaceHtml (destroy & create): 703ms (39.8x faster)
Done.
IE7
15000 elements…
innerHTML (destroy only): 94ms
innerHTML (create only): 391ms
innerHTML (destroy & create): 406ms
replaceHtml (destroy only): 78ms (1.2x faster)
replaceHtml (create only): 359ms (1.1x faster)
replaceHtml (destroy & create): 422ms (1.0x slower)
Opera 9
15000 elements…
innerHTML (destroy only): 47ms
innerHTML (create only): 250ms
innerHTML (destroy & create): 578ms
replaceHtml (destroy only): 94ms (2.0x slower)
replaceHtml (create only): 219ms (1.1x faster)
replaceHtml (destroy & create): 328ms (1.8x faster)
Done.
测试页面在这里
Leave a reply