var data = { Array.from(Array(10000).keys()) };
Object.fromEntries(Object.entries(data).map((key, value) => [key, value]));
Object.entries(data).reduce((acc, [k, v]) => {
acc[k] = v.toString();
return acc;
}, {});
Object.entries(data).reduce((acc, [k, v]) => ({
acc,
[k]: v.toString()
}), {});
const res = {};
Object.entries(data).forEach((key, value) => {
res[key] = value;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) | |
For-each |
Test name | Executions per second |
---|---|
Object.fromEntries | 341.4 Ops/sec |
Reduce (reuse object) | 2960.0 Ops/sec |
Reduce (creating temporary objects) | 92.7 Ops/sec |
For-each | 327.9 Ops/sec |
The benchmark provided compares four different JavaScript methods of constructing an object from an array of key-value pairs (derived from a given dataset). The dataset consists of numbers from 0 to 9999, mapped as key-value pairs in an object. Below is an analysis of the tested methods, their respective pros and cons, and other considerations.
Object.fromEntries(Object.entries(data).map((key, value) => [key, value]));
Description: This method uses Object.entries()
to convert the data
object into an array of key-value pairs, which is then transformed by map
. Finally, Object.fromEntries()
converts the array of pairs back into an object.
Pros:
Cons:
map()
.Object.entries(data).reduce((acc, [k, v]) => {
acc[k] = v.toString();
return acc;
}, {});
Description: This approach uses reduce()
to iterate over the key-value pairs from Object.entries()
, reusing the accumulator object (acc
) to build the final result.
Pros:
Cons:
Object.fromEntries()
, which may impact readability for those unfamiliar with reduce()
.Object.entries(data).reduce((acc, [k, v]) => ({
...acc,
[k]: v.toString()
}), {});
Description: Similar to the previous reduce method, but it uses the spread operator (...
) to create new objects for each iteration, effectively generating a new object based on the existing one.
Pros:
Cons:
const res = {};
Object.entries(data).forEach((key, value) => {
res[key] = value;
});
Description: This method initializes an empty object and uses forEach()
to iterate through Object.entries()
, populating the result object.
Pros:
Cons:
reduce()
method since it doesn't leverage the accumulator pattern and might be slower due to individual property assignments.According to the benchmark results:
map()
and fromEntries()
.Object.fromEntries
at 327.88 executions per second.Overall, understanding the trade-offs between readability and performance aids in selecting the best methodology for constructing objects from key-value pairs in JavaScript.