var arr = new Array({ length: 10000 }, () => Math.floor(Math.random() * 1000));
var isGreaterThan500 = val => val > 500;
var filtered = arr.filter(isGreaterThan500)
var l = arr.length
var filtered = [];
for (var i = 0; i < l; i++) {
var val = arr[i];
if (val > 500) {
filtered.push(val);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array_filter_method | |
classic_for_loop_filter |
Test name | Executions per second |
---|---|
Array_filter_method | 5464414.5 Ops/sec |
classic_for_loop_filter | 3971685.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Overview
The benchmark compares two approaches to filter an array of numbers: using the Array.prototype.filter()
method (which is often referred to as "filtering") and implementing a handwired for loop to achieve the same filtering result.
Test Cases
There are two test cases:
Array_filter_method
: This test case uses the built-in Array.prototype.filter()
method to filter the array.classic_for_loop_filter
: This test case implements a handwired for loop to filter the array, which means manually iterating over each element and adding it to an output array if the condition is met.Comparison
The benchmark compares the execution time of these two approaches on a large array (10,000 elements) generated with JavaScript's Array()
constructor.
Options Compared
Array.prototype.filter()
: This approach uses a built-in method to filter the array.Pros and Cons of Each Approach
Array.prototype.filter()
:Array.prototype.filter()
method.Library Usage
There are no external libraries used in this benchmark. The Array
constructor and basic JavaScript operators (e.g., >
, push
) are part of the language itself.
Special JS Features or Syntax
None mentioned.
Other Alternatives
If you're looking for alternative approaches to filtering arrays, some other options include:
Array.prototype.reduce()
with a custom callback function.Array.prototype.slice()
).Keep in mind that the best approach will depend on the specific use case, performance requirements, and personal preference.