让前端飞

JS中Object.create(null)和{}遍历速度的对比

2023-10-07  本文已影响0人  来一斤BUG

对比

对比方法:分别用Object.create(null){}的方式创建两个对象,使用for ... in循环遍历两个对象,且分别重复一亿次,然后使用console.time()打印消耗的时间

提示:Object.create(null)创建的对象没有原型链,而{}创建的对象有原型Object

const obj1 = Object.create(null, {name: {value: "obj1", enumerable: true}});
const obj2 = {name: "obj2"};

console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));

const count = 100000000;

console.time("obj1");
for (let i = 0; i < count; i++) {
    for (let key in obj1) {
    }
}
console.timeEnd("obj1");

console.time("obj2");
for (let i = 0; i < count; i++) {
    for (let key in obj2) {
    }
}
console.timeEnd("obj2");

输出:

{"name":"obj1"}
{"name":"obj2"}
obj1: 12907.241ms
obj2: 502.186ms

可以看到两者的遍历速度相差了两个数量级

const obj1 = Object.create(null);
const obj2 = {};

console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));

const count = 100000000;

console.time("obj1");
for (let i = 0; i < count; i++) {
    for (let key in obj1) {
    }
}
console.timeEnd("obj1");

console.time("obj2");
for (let i = 0; i < count; i++) {
    for (let key in obj2) {
    }
}
console.timeEnd("obj2");

输出:

{}
{}
obj1: 434.401ms
obj2: 429.515ms

两个对象都为空时,遍历速度几乎是一样的。有时候obj1快,有时候obj2快,可以忽略不计

有意思的是,当删除console.log(JSON.stringify(obj1));console.log(JSON.stringify(obj2));之后,几乎每次都是obj1更快

obj1: 411.146ms
obj2: 431.737ms

obj1: 410.746ms
obj2: 428.895ms

obj1: 410.106ms
obj2: 429.867ms

obj1: 412.137ms
obj2: 451.738ms
const obj1 = Object.create(null, {name: {value: "obj1", enumerable: false}});
const obj2 = {};
Object.defineProperty(obj2, "name", {value: "obj2", enumerable: false});

console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));

const count = 100000000;

console.time("obj1");
for (let i = 0; i < count; i++) {
    for (let key in obj1) {
    }
}
console.timeEnd("obj1");

console.time("obj2");
for (let i = 0; i < count; i++) {
    for (let key in obj2) {
    }
}
console.timeEnd("obj2");

输出:

{}
{}
obj1: 5644.592ms
obj2: 427.602ms

依然是obj2快,速度相差一个数量级

结论

在大多数情况下,使用{}对象进行遍历效率更高,猜测是两者底层的数据结构差别较大或者是{}对象内部进行了优化。一般用{}创建对象即可,除非有特殊需求

上一篇 下一篇

猜你喜欢

热点阅读