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 |
This benchmark tests three different approaches to filtering an array of mixed data types in JavaScript:
1. filter()
Method:
.filter()
method, which iterates over each element in the array and returns a new array containing only elements that pass a specific test (a function provided as an argument).2. for
Loop:
for
loop to iterate over the array's indices and conditionally add each element to a new array (farr
)..filter()
, can be less efficient due to potential overhead compared to optimized methods like .filter()
.3. for...in
Loop:
for...in
loop to iterate over the keys of the array (which are numerically indexed in this case). It then accesses the elements using these keys and adds them to the new array (farr
).for
loop.Considerations:
.filter()
method is generally considered the most efficient and readable approach for filtering arrays in JavaScript. It leverages built-in optimizations and provides a clear syntax.for
loop might be more suitable.for...in
loops are best suited for iterating over object properties, not arrays. Using them for arrays can lead to performance issues.Let me know if you have any other questions about this benchmark!