JavaScript map vs object performance Maps can be slower:
Due to the .get
function call overhead and lack of internal optimisation, Map can be considerably slower than a plain old JavaScript object for some tasks.
Map tends to have more advantages over Object in scenarios when we just need a simple look-up structure for data storing, with all the basic operations it provided.
JavaScript map vs object performance
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
let obj = {},
map = new Map(),
n = 1000000;
for (let i = 0; i < n; i++) {
obj[i] = i;
map.set(i, i);
}
</script>
</body>
</html>
Results consistently show performance gains when using Maps, especially when adding and deleting entries.
Finding Entries
<!DOCTYPE html> <html> <body> <script> let obj = {}, map = new Map(), n = 1000000; for (let i = 0; i < n; i++) { obj[i] = i; map.set(i, i); } let result; console.time('Object'); result = obj.hasOwnProperty('999999'); console.timeEnd('Object'); console.time('Map'); result = map.has(999999); console.timeEnd('Map'); </script> </body> </html>
Output:
Adding Entries
console.time('Object');
obj[n] = n;
console.timeEnd('Object');console.time('Map');
map.set(n, n);
console.timeEnd('Map');
Object: 0.229ms
Map: 0.005ms (45.8 times faster!)
Deleting Entries
console.time('Object');
delete obj[n];
console.timeEnd('Object');console.time('Map');
map.delete(n);
console.timeEnd('Map');
Object: 0.376ms
Map: 0.012ms (31 times faster!)
Where Maps Are Slower
When using a for
loop to create our original object and map. This result is surprising, since without the for
loop, adding entries to a Map outperformed adding entries to a standard object.
let obj = {}, map = new Map(), n = 1000000;
console.time('Map');for (let i = 0; i < n; i++) {
map.set(i, i);
}
console.timeEnd('Map');console.time('Object');
for (let i = 0; i < n; i++) {
obj[i] = i;
}
console.timeEnd('Object');
Object: 32.143ms
Map: 163.828ms (5 times slower)
Soruce: https://bretcameron.medium.com
Do comment if you have any doubts or suggestions on this Js map vs object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version