var ppl = []
for(var i=0; i<10000; i++) {
ppl.push({ id: i, name: i+"" })
}
var byId = ppl.reduce((stored, current) => ({ stored, [current.id]: current }), {});
var byId = {}
for(var i=0;i<ppl.length;i++) {
byId[ppl[i].id] = ppl[i]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
forcycle |
Test name | Executions per second |
---|---|
reduce | 36.4 Ops/sec |
forcycle | 327.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided JSON represents two test cases for a benchmark that compares the performance of two approaches to create an object from an array: using Array.prototype.reduce()
and using a for
loop with indexing. The goal is to determine which approach is faster.
Options Compared
Two options are compared:
reduce()
: This method applies a user-supplied function to each element in the array, accumulating a value or object.forcycle
(for loop with indexing): A traditional for
loop that iterates over the array, assigning each element to an object using its index as the key.Pros and Cons of Each Approach
reduce()
:
Pros:
Cons:
forcycle
:
Pros:
Cons:
reduce()
Library and Special JS Feature
In this benchmark, no libraries are explicitly mentioned, but it's possible that the Array.prototype.reduce()
method relies on internal implementations provided by the ECMAScript standard.
No special JavaScript features are used in these test cases.
Benchmark Preparation Code
The provided script preparation code creates an array of 10,000 objects with unique id
and name
properties:
var ppl = [];
for (var i = 0; i < 10000; i++) {
ppl.push({ id: i, name: i + "" });
}
The HTML preparation code is not specified, as it's likely that the benchmark runs in a browser environment with an existing DOM.
Latest Benchmark Result
The latest result shows two test cases:
forcycle
: With 327 executions per second on a Chrome 85 browser on a Windows desktop.reduce()
: With 36 executions per second on the same browser and hardware configuration.These results suggest that, in this specific case, the forcycle
approach is significantly faster than using Array.prototype.reduce()
.
Other Alternatives
If you're interested in exploring other approaches for creating an object from an array, consider these alternatives:
Object.assign()
or Array.prototype.map()
lodash
or ramda
Keep in mind that the best approach depends on your specific use case and performance requirements. MeasureThat.net's benchmark results can serve as a starting point for further optimization and exploration.