JavaScript中有几种常用的清空变量的方式:delete、设为null、设为undefined。
它们的性能差异如何呢?
结论
- 赋值为undefined或null,比delete快近70倍!!
- 并且也没有看出明显的内存差异。
delete
正向delete
(()=>{
let totalTime = 0, N=10;
for(let n=0; n<N; ++n){
let a = {};
for(let i=0; i<1000000; ++i){
a[i] = i;
}
let startTime = Date.now();
for(let i=0; i<1000000; ++i){
delete a[i];
}
totalTime += Date.now() - startTime;
a;
}
console.log(`avg ${totalTime/N}ms in ${N} times`);
})()
结果
avg 67.5ms in 10 times
反向delete
(()=>{
let totalTime = 0, N=10;
for(let n=0; n<N; ++n){
let a = {};
for(let i=0; i<1000000; ++i){
a[i] = i;
}
let startTime = Date.now();
for(let i=1000000-1; i>-1; --i){
delete a[i];
}
totalTime += Date.now() - startTime;
a;
}
console.log(`avg ${totalTime/N}ms in ${N} times`);
})()
结果
avg 64.4ms in 10 times
结论
delete 反向好像比正向快那么一丁点
set to undefined
正向
(()=>{
let totalTime = 0, N=10;
for(let n=0; n<N; ++n){
let a = {};
for(let i=0; i<1000000; ++i){
a[i] = i;
}
let startTime = Date.now();
for(let i=0; i<1000000; ++i){
a[i] = undefined;
}
totalTime += Date.now() - startTime;
a;
}
console.log(`avg ${totalTime/N}ms in ${N} times`);
})()
结果!!!!!
avg 0.8ms in 10 times
(正文完)