var arr = [1,2,3,4,5,6,7,8,9,0], farr;
farr = arr.filter(function(item) { return (item>4); } );
for (var i=0,len=arr.length;i<len;i++) {
if (arr[i]<5) continue;
farr.push(arr[i]);
}
for (var i=0,len=arr.length;i<len;i++) {
if (arr[i]>4) farr.push(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter | |
For | |
For 2 |
Test name | Executions per second |
---|---|
Filter | 10036123.0 Ops/sec |
For | 1454699.5 Ops/sec |
For 2 | 997605.2 Ops/sec |
Let's break down what is tested in this benchmark, and I'll explain the different options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark measures the performance of two approaches to filter an array:
Array.prototype.filter()
for
loopThe array arr
is defined with 10 elements, including one element that is out of range (0), which will be ignored by both filters.
Options Compared
There are three test cases:
Array.prototype.filter()
method to create a new array containing only the elements that pass the condition (item > 4
).for
loop to iterate over the array and push elements into a new array (farr
) if they meet the condition (arr[i] < 5
).For
test case, but it checks for arr[i] > 4
instead of arr[i] < 5
.Pros and Cons
item > 4
) is evaluated for each element in the original array, which might be slower if the condition is expensive or unpredictable.i
) needs to be manually updated on each iteration, which can lead to slightly slower performance compared to the built-in filter()
method.Other Considerations
For
tests, the array elements are accessed sequentially (by index), which can improve cache locality. This might give it a small performance boost.arr[i] < 5
) is evaluated for each element, and the branch predictor may make educated guesses about whether to execute the code path based on the element's value. This can lead to minor performance variations.Library Usage
None of the test cases use any external libraries.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark. The tests only rely on standard JavaScript language and library features.
Alternative Approaches
Other approaches that could be tested include:
Array.prototype.map()
instead of filter()
Set
data structure to keep track of filtered elementsHowever, these alternatives would likely require significant modifications to the benchmark definition and test cases to accurately measure their performance impact.