let obj = {};
for (let i = 0; i < 1000000; i++) {
obj[i] = i;
}
let tuples = Object.entries(obj).map(([k, v]) => [k, v]);
let map = new Map();
for (let i = 0; i < 1000000; i++) {
map.set(i, i);
}
let tuples = [map].map(([k, v]) => [k, v]);
let map = new Map();
for (let i = 0; i < 1000000; i++) {
map.set(i, i);
}
let tuples = Array.from(map).map(([k, v]) => [k, v]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Obj / Object.entries() | |
Map / spread | |
Map / Array.from() |
Test name | Executions per second |
---|---|
Obj / Object.entries() | 6.2 Ops/sec |
Map / spread | 7.5 Ops/sec |
Map / Array.from() | 7.7 Ops/sec |
The benchmark represented in the provided JSON is focused on comparing different methods of iterating over and converting data structures in JavaScript, specifically between native Objects (or Records in TypeScript) and the built-in Map object. The core operations being tested are the conversion of these data structures into an array of key-value pairs, represented as tuples, using different approaches.
Object / Object.entries()
obj
) with 1,000,000 key-value pairs, where the keys are integers from 0 to 999,999 and the values are the same integers. Then it uses Object.entries()
to convert this object into an array of tuples.Object.entries()
is a built-in and widely supported method.Map / spread
Map
to store 1,000,000 key-value pairs, similar to the object test. It then utilizes the spread operator (...
) to convert the Map into an array of tuples.Map / Array.from()
Map
but converts it into an array with Array.from()
.Array.from()
is explicit about converting iterable objects into arrays and can be more flexible with additional mapping functions.The benchmark results indicate that among the tested methods, the Map / Array.from()
approach yielded the highest number of executions per second, suggesting that it might be the most efficient option for converting a Map to an array of tuples. The Map / spread
was slightly slower but still performs better than using Object.entries()
on the plain object. The plain object approach was the slowest, which aligns with the expectation that converting a large object could have more overhead than that of a Map.
Array.from()
is largely a matter of personal preference and readability for the given context.Other approaches for similar operations might include:
for
loop can sometimes yield better performance in specific cases, especially when optimized for the particular dataset.Array.prototype.reduce()
method could also be an alternative way of transforming objects into arrays, although it might not be as straightforward and have more overhead.Overall, this benchmark helps highlight performance considerations when choosing between ordinary objects and Maps in JavaScript for similar operations.