PRIMARY_SCOPES = ['a', 'd']
availableScopes = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}
const output = PRIMARY_SCOPES.filter((scope) => scope in availableScopes).reduce(
(result, scope) => ({
result,
[scope]: availableScopes[scope],
}),
{},
);
PRIMARY_SCOPES = ['a', 'd']
availableScopes = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}
const output = {};
Object.entries(availableScopes).forEach(([key, value]) => {
if (!PRIMARY_SCOPES.includes(key)) {
return;
}
Object.assign(output, { [key]: value });
});
return output;
PRIMARY_SCOPES = ['a', 'd']
availableScopes = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}
const output = {};
PRIMARY_SCOPES.filter((scope) => scope in availableScopes).forEach((scope) => {
Object.assign(output, { [scope]: availableScopes[scope] });
});
return output;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using array filter and reduce + spread | |
Using array filter and object assign | |
Using array filter and object assign SMALLER array first |
Test name | Executions per second |
---|---|
Using array filter and reduce + spread | 582422.5 Ops/sec |
Using array filter and object assign | 432107.6 Ops/sec |
Using array filter and object assign SMALLER array first | 523630.8 Ops/sec |
Let's break down the provided benchmark and explain what is tested, the pros and cons of different approaches, and other considerations.
Benchmark Test Cases
The test cases compare three different ways to create an object from an array of scopes using two arrays: PRIMARY_SCOPES
and availableScopes
. The test aims to measure the performance difference between these approaches.
filter()
method to select only the scopes that exist in availableScopes
, then applies the reduce()
method to create an object from the filtered scopes.forEach()
method instead of reduce()
. The second variant uses PRIMARY_SCOPES.filter()
and then iterates over the result using another forEach()
call.PRIMARY_SCOPES
before filtering the scopes.Library Used
None of the test cases explicitly use any external libraries.
Special JavaScript Features or Syntax
The benchmark uses some ES6+ syntax features:
const
: used for variable declarationslet
and var
: not used in this benchmark, but it's worth mentioning that they are still valid optionstemplate literals
: not used directly, but the spread operator (...
) is used inside a template literal (although it can be used without one)Object.entries()
, Object.assign()
: these methods were introduced in ECMAScript 2015 (ES6)Pros and Cons of Different Approaches
reduce()
with an initial valuereduce()
reduce()
due to the overhead of the forEach()
methodPRIMARY_SCOPES
before filteringOther Considerations
availableScopes
object or a scope that is not present in both arrays.Alternatives
If you were to rewrite this benchmark with different approaches, here are some alternatives:
forEach()
or reduce()