var data = { Array.from(Array(10000).keys()) };
Object.fromEntries(Object.entries(data).filter((key, value) => value % 2 === 0));
Object.entries(data).reduce((acc, [key, value]) => {
if (value % 2 === 0) {
acc[key] = value;
}
return acc;
}, {});
Object.entries(data).reduce((acc, [k, v]) => ({
acc,
v % 2 === 0 && {[k]: v}) (
}), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) |
Test name | Executions per second |
---|---|
Object.fromEntries | 735.2 Ops/sec |
Reduce (reuse object) | 979.6 Ops/sec |
Reduce (creating temporary objects) | 0.2 Ops/sec |
Let's break down the benchmark and its various components.
Benchmark Overview
The benchmark compares three approaches to filter keys in an object:
Object.fromEntries
with a filtered array of key-value pairs.reduce()
method on the Object.entries()
iterator, reusing an accumulator object for each iteration.reduce()
method on the Object.entries()
iterator, creating temporary objects for each iteration.Options Compared
The benchmark compares the performance of these three approaches:
Object.fromEntries()
method to create an object from an array of key-value pairs. The filtered array is created using the filter()
method.reduce()
method on the Object.entries()
iterator, reusing an accumulator object for each iteration. The accumulator is initialized as an empty object {}
and updated with the filtered key-value pairs.reduce()
method on the Object.entries()
iterator, but creates a new temporary object for each iteration instead of reusing an existing one.Pros and Cons
Here are some pros and cons of each approach:
Library Used
None of the benchmark options explicitly use any external libraries. However, Object.entries()
is a built-in JavaScript method that returns an array-like iterator over the key-value pairs of an object.
Special JS Features or Syntax
The benchmark uses several advanced JavaScript features:
reduce()
method, which is a part of the Array prototype....
), used to create new objects in Approach 3.=>
), used in the callback function of the reduce()
method.These features are not specific to JavaScript and can be found in many other programming languages.
Alternatives
Other alternatives for filtering keys in an object include:
data[key] === value % 2 ? data[key] : undefined
).filter()
method on an array of key-value pairs, followed by creating an object from the filtered array using the Object.fromEntries()
method.pickBy()
function for filtering keys in objects.These alternatives may have different performance characteristics and code readability compared to the benchmark options.