关于appendChild和insertBefore的性能测试
作者:秋了秋 发表时间:2021年12月24日
最近在项目中需要用到insertBefore插入文档替代appendChild, 用的时候在考虑appendChild和insertBefore到底有没有区别,有多大的区别。于是做了个小实验。以下是实验代码:
const count = 500000, timeout = 1000; const flag = document.createDocumentFragment(); const lastDiv = document.createElement('div'); lastDiv.className = 'lastDiv'; flag.appendChild(lastDiv);//先预先埋好基线,避免基线对性能测试带来影响 let newDiv; //采用延时,让cpu歇一会,减少对实验的干扰 setTimeout(function() { console.time('appendChild'); for(let i = 0; i < count; i++) { newDiv = document.createElement('div'); flag.appendChild(newDiv); } console.timeEnd('appendChild'); }, timeout); //采用延时,让cpu歇一会,减少对实验的干扰。第一个延时是等待上面的执行完,第二个延时才是让cpu缓一缓 setTimeout(function() { setTimeout(function() { console.time('insertBefore'); for(let i = 0; i < count; i++) { newDiv = document.createElement('div'); flag.insertBefore(newDiv, lastDiv); } console.timeEnd('insertBefore'); }, timeout); }, timeout);
测试结果:
appendChild: 707.77001953125 ms
insertBefore: 710.93115234375 ms
经过多次测试取平均值发现insertBefore要比appendChild慢一些,但不是很明显,还可以接受。所以在日常使用中可忽略这种差异。
3
文章作者: “秋了秋”个人博客,本站鼓励原创。
转载请注明本文地址:http://netblog.cn/blog/94.html