var arr = ['a', 'b', 'c'];
arr.reduce((curr, acc) => { if(curr === 'a') return [curr, acc]; return curr }, [])
arr.map(curr => curr === 'a' ? curr : undefined).filter(Boolean)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
map+filter |
Test name | Executions per second |
---|---|
reduce | 26005992.0 Ops/sec |
map+filter | 3810817.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is testing two approaches to achieve the same result: reducing an array of strings using either reduce()
or mapping the array, filtering out non-matching elements, and then filtering out falsy values (undefined
in this case).
Options Compared
reduce()
method applies a callback function to each element in the array, accumulating a result. In this case, the callback function checks if the current element is 'a'. If it is, it returns a new array with the current element and the accumulated result (initially an empty array). If not, it returns the original accumulated result. The filter(Boolean)
step removes any falsy values from the resulting array.map()
method to transform each element in the array into a boolean value (true
if 'a' matches and false
otherwise), then filters out non-boolean values using filter(Boolean)
. The final result is an array of only the elements that passed the filter.Pros and Cons
Library and Special JS Features
Neither reduce()
nor map() + filter()
rely on any specific libraries. However, these methods are built-in to JavaScript and are used extensively in web development.
Other Considerations
reduce()
approach might be more efficient due to its reduced number of iterations.map() + filter()
approach might be faster due to its concise nature.Alternatives
If you were to rewrite this benchmark using alternative approaches, here are a few options:
reduce()
or map()
, you could use the forEach
method to iterate over the array and accumulate the results.Keep in mind that these alternative approaches would likely be less efficient than the original reduce()
and map() + filter()
methods.