Javascript Map delete / set is slow [duplicate]

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?


Solution 1:

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