const arr = [
{name: 'name1', prop: 'prop'},
{name: 'name2', prop: 'prop'},
{name: 'name3', prop: 'prop'},
{name: 'name4', prop: 'prop'}
]
const obj = {};
arr.forEach(a => obj[a.name] = a)
const arr = [
{name: 'name1', prop: 'prop'},
{name: 'name2', prop: 'prop'},
{name: 'name3', prop: 'prop'},
{name: 'name4', prop: 'prop'}
]
const mp = new Map();
arr.forEach((a) => {
mp.set(a.name, a);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using Object | |
Using Map() |
Test name | Executions per second |
---|---|
Using Object | 15674384.0 Ops/sec |
Using Map() | 6472529.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
MeasureThat.net is testing two approaches to achieve the same result: using Object
and using Map()
in JavaScript. Specifically, it's comparing how efficient these two methods are when iterating over an array and assigning values to an object.
Options compared
There are two main options being compared:
Object
: This approach uses a traditional object literal to create an empty object, and then iterates over the array using forEach()
, assigning each element as a property of the object.Map()
: This approach uses the Map()
constructor to create an empty map (a hash table-like data structure), and then iterates over the array using forEach()
, setting each element as a key-value pair in the map.Pros and Cons
Here's a brief rundown of the pros and cons of each approach:
Object
Pros:
Cons:
Map()
Pros:
Cons:
Map()
APILibrary and purpose
The Map
data structure is a built-in JavaScript API introduced in ECMAScript 2015 (ES6). It provides a way to store key-value pairs, allowing for fast lookups and efficient insertion/deletion of elements.
Special JS feature or syntax
There are no special features or syntax required to run this benchmark. However, it's worth noting that the Map()
API is supported by most modern browsers, including Chrome 107, which is used in this benchmark.
Other alternatives
While not explicitly tested in this benchmark, other approaches could be considered:
for...in
loop with an object literalmapValues()
functionThese alternatives might offer different performance characteristics, but they are not part of the original implementation described in the benchmark.