var arr = [1,2,3,4,null,5,6,"7",8,{a:2},0], farr=[], i,len;
farr= arr.filter(function(item) {
return (item);
});
farr = [];
for (i=0,len=arr.length;i<len;i++) {
farr.push(arr[i]);
}
farr = [];
for(i in arr) {
farr.push(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter | |
For | |
For in |
Test name | Executions per second |
---|---|
Filter | 5680161.0 Ops/sec |
For | 1084128.9 Ops/sec |
For in | 867330.9 Ops/sec |
Let's dive into the benchmark results.
What is being tested?
The benchmark tests the performance of three different methods for filtering an array:
filter()
method (ECMAScript 5)for
loopfor...in
loopOptions compared:
We're comparing three approaches to filtering an array:
filter()
method is a built-in JavaScript function that creates a new array with all elements that pass the test implemented by the provided function.for
loop iterates over an array, and we're using it to create a new array with filtered elements.for...in
loop is used to iterate over an object's enumerable properties. However, in this case, we're using it to iterate over the array indices.Pros and cons of each approach:
filter()
since it avoids function calls.for
loops when dealing with sparse arrays (arrays containing gaps in the indices).Other considerations:
filter()
method is a built-in ECMAScript 5 feature, which means it might not be supported in older browsers.some()
and every()
methods or a combination of forEach()
and conditional statements.Test case explanations:
filter()
method to create a new array with all elements that are truthy (i.e., not null or undefined).for
loop to achieve the same result.for...in
loop, which is generally discouraged when iterating over arrays.Benchmark results:
The benchmark results show that the filter()
method performs best on this particular task, followed by the for
loop, and then the for...in
loop. However, please note that these results are specific to the test environment and might vary depending on your system configuration and browser.