<!--your preparation HTML code goes here-->
var data = { Array.from(Array(10000).keys()) };
Object.fromEntries(Object.entries(data || {}).filter((d) => d[1]));
Object.entries(data).reduce(
(acc, [key, value]) =>
value === undefined ? acc : { acc, [key]: value },
{}
);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter | |
reduce |
Test name | Executions per second |
---|---|
filter | 689.5 Ops/sec |
reduce | 26.0 Ops/sec |
The benchmark from MeasureThat.net compares two different JavaScript methodologies for filtering objects: using the filter
approach and the reduce
approach. Both methods are being tested for their performance in processing a dataset, specifically an object created from an array of numbers ranging from 0 to 9999.
Filter Method:
Object.fromEntries(Object.entries(data || {}).filter((d) => d[1]));
data
object into an array of entries (key-value pairs) using Object.entries()
, filters those entries based on a condition (in this case, it keeps entries only where the value is truthy), and finally converts the filtered entries back into an object using Object.fromEntries()
.Reduce Method:
Object.entries(data).reduce(
(acc, [key, value]) => value === undefined ? acc : { ...acc, [key]: value },
{}
);
data
object into an array of entries. It then uses reduce
to accumulate a new object that contains only the entries where values are defined (filtering out undefined)....acc
) inside the reduce can be costly in terms of performance because it creates a new object in each iteration, leading to potential overhead in memory and processing time.In the latest benchmark results, the following performance metrics were reported:
From the results, it is clear that the filter
method significantly outperforms the reduce
method in terms of speed in this particular implementation. This indicates that for scenarios where performance is critical, especially when processing large datasets, using the filter
method may be the better choice.
In addition to these methods, there are other techniques to filter an object that could be considered:
For Loop:
for
loop can be used to manually create a new object by iterating over the keys of the original object. This method offers the most control in terms of performance optimization.For...in Loop:
for...in
loop to iterate over the object's properties can provide an alternative that is similarly performant to a standard for loop.hasOwnProperty
.Using Libraries (like Lodash):
_.pickBy
, etc.) that handle object manipulation and filtering more succinctly.In conclusion, while both filter
and reduce
have their use cases and strengths, the benchmark results favor the filter
method for performance efficiency in this specific context. Software engineers can choose between methods based on their specific performance needs, code readability requirements, and preferences for functional versus imperative programming paradigms.