var array = [Array(100000).keys()];
function fastFilter(arrayToFilter, cb) {
const stack = []
for (let i = 0; i < arrayToFilter.length; i += 1) {
const item = arrayToFilter[i]
if (cb(item, i)) {
stack.push(item)
}
}
return stack
}
array.filter(n => n === 99999)
fastFilter(array, n => n === 99999)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.filter | |
for loop filter |
Test name | Executions per second |
---|---|
Array.prototype.filter | 2242.9 Ops/sec |
for loop filter | 15007.3 Ops/sec |
Benchmark Explanation
The provided benchmark compares two approaches to filtering an array of numbers in JavaScript:
n => n === 99999
).fastFilter
function: This is a custom implementation of a filtering function written in JavaScript. It uses a stack-based approach to iterate over the array and push elements that pass the test.Options Compared
The benchmark compares two options:
fastFilter
function: This is a custom implementation of a filtering function written in JavaScript.Pros and Cons
Pros:
Cons:
fastFilter
functionPros:
Cons:
Library Usage
In this benchmark, neither library is explicitly used. However, JavaScript's built-in Array.prototype.filter
method relies on various libraries and implementations under the hood, such as:
Special JS Features or Syntax
None are mentioned in this specific benchmark.
Other Alternatives
For filtering arrays, other approaches could include:
forEach()
: Iterate over the array using a callback function, which can be useful for tasks that require iteration but don't need to filter out elements.map()
and filter()
combination: Apply the map()
method to create a new array with transformed elements, and then apply the filter()
method to remove unwanted elements.reduce()
: Use the accumulator-based reduction function to process elements in the array.These alternatives may offer trade-offs in terms of performance, memory usage, or code complexity, depending on the specific use case.