至少在这个例子中,似乎ECMAScript 6 Map的检索速度比使用对象慢。在Firefox中,使用以下代码:
map = {};
var i=1000000;
console.time('populate');
while (i--) {
map[i] = 'value of '+i;
}
console.timeEnd('populate');
console.time('has');
var i=2000000;
var ctr = 0;
while (i--) {
if (map.hasOwnProperty(i)) {
ctr++;
}
}
console.timeEnd('has');
console.log(ctr)
map = new Map();
var i=1000000;
console.time('populate');
while (i--) {
map.set(i, 'value of '+i);
}
console.timeEnd('populate');
console.time('has');
var i=2000000;
var ctr = 0;
while (i--) {
if (map.has(i)) {
ctr++;
}
}
console.timeEnd('has');
console.log(ctr)
map = {};
var i=1000000;
console.time('populate');
while (i--) {
map[i] = 'value of '+i;
}
console.timeEnd('populate');
console.time('has');
var i=2000000;
var ctr = 0;
while (i--) {
if (map.hasOwnProperty(i)) {
ctr++;
}
}
console.timeEnd('has');
console.log(ctr)
输出结果为:
populate: timer started Maptest:16
populate: 465.51ms Maptest:20
has: timer started Maptest:22
has: 133.03ms Maptest:30
1000000 Maptest:31
populate: timer started Maptest:39
populate: 418.26ms Maptest:43
has: timer started Maptest:45
has: 414.44ms Maptest:53
1000000 Maptest:54
populate: timer started Maptest:60
populate: 347.55ms Maptest:64
has: timer started Maptest:66
has: 124.67ms Maptest:74
1000000
为什么检查速度比对象检查慢4倍?
答案 0 :(得分:1)
在我看来就像缓存效果一样。如果我减少Map中的项目数量以使其适合我的缓存,我会更快 查找....