Van*_*ing 6 javascript performance dom google-chrome
我有一个框架,可以完全使用document.createElement和生成应用程序的DOM document.appendChild.现在应用程序变得越来越大,我注意到Chrome需要比其他浏览器更长的时间来构建DOM.
所以,我创建了以下性能测试:
window.onload = function(){
var now = new Date().getTime();
for(var i = 0; i < 10000; i++){
document.body.appendChild(document.createElement("div"));
}
setTimeout(function(){
console.log(new Date().getTime() - now);
},0);
}
Run Code Online (Sandbox Code Playgroud)
这个测试的结果非常有趣:
Chrome的完成时间比Opera多14倍.这不仅仅是一个毫无意义的基准!我真的可以在我的应用中感受到这种差异.
Chrome在DOM操作中的速度是否正常?有没有办法加快速度?
谢谢!
小智 5
更新2
这是一种hackish类型的解决方案,可能值得一点浏览器检测.它带来了在我的测试中性能下降到不到1/10的那是什么.
您可以display='none'在追加容器之前将容器再次显示出来.你可能会得到一点点闪光,但这可能比长时间延迟更好.
window.onload = function(){
var content = String.fromCharCode(Math.floor(Math.random() * 1000));
// cache it in case it is already set
var disp = document.body.style.display;
document.body.style.display = 'none';
var now = new Date().getTime();
for(var i = 0; i < 10000; i++){
document.body.appendChild(document.createElement("div"))
.appendChild(document.createTextNode( content ));
}
setTimeout(function(){
console.log(new Date().getTime() - now);
document.body.style.display = disp || ''; // restore it
},0);
};
Run Code Online (Sandbox Code Playgroud)
这是我所期望的那种性能提升documentFragment.
更新
运行后,修改后的版本的@ Esailija的的jsfiddle测试,包括DocumentFragment的,它似乎并没有做(为此事或Opera)在Chrome任何区别,因此它看起来好像Chrome是简单地慢.
"有没有办法加快速度?"
我猜你如果你使用a documentFragment,你会获得更好的性能,然后用一个单独附加到DOM .appendChild.
window.onload = function(){
var now = new Date().getTime();
// create a documentFragment
var frag = document.createDocumentFragment();
for(var i = 0; i < 10000; i++){
frag.appendChild(Div()); // append to the documentFragment
}
// append the documentFragment (which is emptied)
document.body.appendChild(frag);
setTimeout(function(){
console.log(new Date().getTime() - now);
},0);
function Div(){
var This = document.createElement("div");
return This;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 0
我觉得这很正常....
HTML 对象操作(宽度、高度和不透明度)也是如此,尤其是在使用 CSS3 时。
我编写了一个幻灯片(不使用 jQuery,我讨厌它),它在 FF、IE、Opera、Safari 等中运行顺利...但不是 Chomre。在 Chrome 中,速度慢得令人难以置信(仅在较新的 Chrome 版本中,在旧版本(如 v12)中速度更快)。
| 归档时间: |
|
| 查看次数: |
3741 次 |
| 最近记录: |