var rows = []
for (let i = 0; i < 10000; i++) {
rows.push(i)
}
var res = rows.reduce(
(acc, curr) => ({
acc,
[curr]: curr,
}),
{}
)
var res = {}
for (let i = 0; i < rows.length; i++) {
res[i] = i
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
non spread |
Test name | Executions per second |
---|---|
spread | 53.6 Ops/sec |
non spread | 2014.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark compares two approaches to creating an object with 10,000 key-value pairs:
...
) to create a new object.res[i] = i
).Options Compared
The benchmark tests two options:
...
)rows
are added as keys to the new object.var res = rows.reduce((acc, curr) => ({ ...acc, [curr]: curr }), {})
dot notation
)for
loop and assigns values to each key in the object using dot notation.var res = {}; for (let i = 0; i < rows.length; i++) { res[i] = i }
Pros and Cons
...
)Pros:
Cons:
dot notation
)Pros:
Cons:
Library and Special JS Features
The benchmark uses the reduce()
method from the Array prototype, which is a part of the ECMAScript standard. There are no other libraries or special JS features used in this benchmark.
Other Considerations
When choosing between these two approaches, consider the trade-offs between conciseness, readability, performance, and control over the creation process.
If you prioritize code brevity and readability, the spread operator (...
) might be a better choice. However, if you're working with very large datasets or need fine-grained control over the creation process, manual iteration (dot notation
) might be more suitable.
Alternatives
Other alternatives for creating objects in JavaScript include:
Object.create()
method to create an object from an existing object._.mapValues()
function, which can simplify the creation process but may introduce additional dependencies.However, these alternatives are not relevant to the specific benchmark at hand, as they don't compare the spread operator and manual iteration directly.