Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Array.forEch vs Array.filter
(version: 1)
Comparing performance of:
foreach if vs filter foreach
Created:
one year ago
by:
Guest
Jump to the latest result
Script Preparation code:
window.arr = []; for(let i = 0; i < 9999; i++) { arr.push(Date.now()) } function cb(v) { console.log(v) }
Tests:
foreach if
window.arr.forEach((v) => { if (v % 2) { cb(v) } })
filter foreach
window.arr.filter((v) => v % 2).forEach((v) => cb(v))
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
foreach if
filter foreach
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
one year ago
)
User agent:
Mozilla/5.0 (Linux; Android 13; Jelly Star Build/TP1A.220624.014; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36 EdgA/124.0.2478.64
Browser/OS:
Chrome Mobile 124 on Android
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
foreach if
7.7 Ops/sec
filter foreach
7.9 Ops/sec
Autogenerated LLM Summary
(model
gpt-4o-mini
, generated one year ago):
The benchmark provided compares two different approaches for processing arrays in JavaScript: using `Array.forEach` with an `if` condition and using `Array.filter` in conjunction with `Array.forEach`. ### Benchmark Overview 1. **Test Cases**: - **forEach with an if statement**: ```javascript window.arr.forEach((v) => { if (v % 2) { cb(v) } }); ``` This test iterates through all elements in `window.arr` and executes the `cb` function for each element that is odd (i.e., when the value of `v` modulo 2 is true). - **Filter followed by forEach**: ```javascript window.arr.filter((v) => v % 2).forEach((v) => cb(v)); ``` This first filters the array to obtain only the odd values and then applies the `cb` function to each of those filtered values. 2. **Definitions**: - `cb(v)`: A callback function defined in the preparation code that logs the value `v` to the console. This function is intentionally simple and serves as a placeholder to represent any action taken on the processed elements. ### Comparison of Approaches #### **forEach with if statement** - **Pros**: - **Simplicity**: The approach is straightforward, directly applying the condition to each element in a single pass. - **Memory Efficiency**: It does not create a new array, meaning less memory overhead. - **Cons**: - **Unoptimized**: Every element is evaluated within the loop, using `if` on each iteration which can be slightly slower if the array is large. #### **Filter followed by forEach** - **Pros**: - **Readability**: The intent is clear; it separates the concerns of filtering and processing, which could be easier to understand. - **Functional Approach**: It leverages functional programming practices by processing data in a more declarative manner. - **Cons**: - **Performance Overhead**: This involves two operations: filtering and then mapping the results, which can increase execution time, especially with larger arrays. - **Memory Usage**: A new array is created during the filtering process, leading to greater memory consumption. ### Considerations and Alternatives - **Performance**: The execution speed (expressed in `ExecutionsPerSecond`) for filtering via `filter` combined with `forEach` was slightly better than the direct `forEach` with an `if` condition in this benchmark, but performance can vary based on the nature and size of the data. - **Readability vs. Performance**: Depending on the need—be it clean code or high performance—developers might choose one method over the other. However, the best approach often depends on the specific use case. ### Other Alternatives 1. **Using a traditional for loop**: Using a `for` loop may yield the best performance for large datasets, as it allows explicit control over the iteration. 2. **Reducing calls**: For large arrays or performance-critical sections, using a single pass with a `for` loop that conditionally checks and processes values can be more efficient. 3. **Using `map` and `filter`**: For scenarios where you may want to transform data as you filter it, combining `map` and `filter` can provide both functionality and readability but at the cost of performance due to the creation of intermediate arrays. In summary, both methods have their use case, trade-offs, and potential performance implications based on the data being processed and the computational context. Understanding these nuances is crucial for any software engineer aiming to write efficient JavaScript code.
Related benchmarks:
Array filter vs. for loop (fixed really really)
Array filter vs. for loop (fixed2)
Array filter vs. for loop (fixed 2)
Array filter vs. for loop (fixed)2
Array filter vs. for loop (fixedN)
Object filtered Array loop vs foreach vs map vs while
filter with forEach vs for with if
Some vs. Filter vs. Find, 10 vs 10k
filter vs for performance
Comments
Confirm delete:
Do you really want to delete benchmark?