JavaScript Map比Object慢得多的随机查找? [英] JavaScript Map much slower than Object for random look-ups?

查看:184
本文介绍了JavaScript Map比Object慢得多的随机查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两个片段(来自此jsperf条目):

  let val = 0; 
for(let i of indices){
val + = map.get(i);
}
// ---
let val = 0;
for(let i of indices){
val + = obj [i];
}

这里,地图 地图 obj 是一个纯旧的JavaScript对象( let obj = {} ), code> indices 是一个随机索引数组。已经使用数据预填充了 obj map ,因此查找实际返回数据。查看jsperf的完整代码。



问题:



执行 Map 5倍以上?这只是因为在写作时, Map 仍然是非常新的和未优化的?或者在 Map 查找中有一些开销,总是会阻止它与POJO一样快?



如果它还没有优化,我们期望它比POJO更快地进行随机查找?最终?为什么?为什么不呢?

解决方案

感谢@Bergi为这个答案。



Map 相比,简单JavaScript对象在初始jsperf中执行得很好的原因是因为在引擎盖下,JS引擎可以看到我们正在使用对象一个数组(连续的整数键),所以它假定它是一个数组,可以根据这个做一些优化。 c code code code code code code code code code $还有一个缺点,它需要一个方法调用( map.get(p)),而不是直接属性查找( obj [p ] )。这没有(不能?)优化,如jsperf所示: http: //jsperf.com/map-vs-pojo-lookups


Consider the following two snippets (from this jsperf entry):

let val = 0;
for(let i of indices) {
  val += map.get(i);
}
// ---
let val = 0;
for(let i of indices) {
  val += obj[i];
}

Here, map is a Map, obj is a plain old JavaScript object (let obj = {}), and indices is an array of random indices. Both obj and map have been pre-populated with data so the lookups actually return data. Check out the jsperf for the full code.

Question:

Why does the plain old javascript object out-perform the Map by a factor of 5+? Is this simply because as of writing, Maps are still very new and un-optimised? Or is there some overhead in Map lookups that will always keep it from being as fast as a POJO?

If it's just not optimised yet, can we expect it to be faster than a POJO for random lookups eventually? Why? Why not?

解决方案

Thanks to @Bergi for this answer.

The reason the plain JavaScript object performed so well in the initial jsperf compared to the Map is because under the hood a JS engine can see that we're using the object like it's an array (consecutive integer keys), so it "assumes" that it's an array and can make a bunch of optimisations based on that. Not so with the Map.

But the Map has a further disadvantage in that it requires a method call (map.get(p)), as opposed to a direct property lookup (obj[p]). This hasn't been (can't be?) optimised away as shown by this jsperf: http://jsperf.com/map-vs-pojo-lookups

这篇关于JavaScript Map比Object慢得多的随机查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆