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, Map
s 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?
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, Map
s 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?
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jun 2, 2017 at 5:19 user993683user993683 4- 1 I suspect it's because of the method call overhead. Also, you are abusing the collection(s) as an array, storing only integer indices. For which property access is super-optimised. Try with some type of key. – Bergi Commented Jun 2, 2017 at 5:23
- @Bergi fixed the array (though to be clear, it's not relevant to this question) cheers