问题描述
请考虑以下两个片段(来自):
c code code code code code code code code code $还有一个缺点,它需要一个方法调用( map.get(p)),而不是直接属性查找( obj [p ] )。这没有(不能?)优化,如jsperf所示: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慢得多的随机查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!