Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
For of vs for each
(version: 0)
Comparing performance of:
For of vs Foreach
Created:
3 years ago
by:
Guest
Jump to the latest result
HTML Preparation code:
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
Script Preparation code:
var arr = []; var size = 100000000; for (let i = 0; i < size; i += 1) { arr.push({a: i}); }
Tests:
For of
let twice = 0; for (const el of arr) { twice += 1; }
Foreach
let twice = 0; _.each(arr, function (el, index) { twice += 1; });
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
For of
Foreach
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
gemma2:9b
, generated one year ago):
This benchmark compares the performance of two ways to iterate over an array in JavaScript: **Option 1: `for...of` loop** - This is a modern JavaScript construct specifically designed for iterating over iterable objects like arrays. - **Benchmark Definition:** `for (const el of arr) { twice += 1; }` - It directly accesses each element (`el`) in the array `arr` without needing an index. **Option 2: Underscore.js's `_.each` function** - This uses a third-party library called Lodash (specifically its `_.each` function). - **Benchmark Definition:** `_.each(arr, function (el, index) { twice += 1; });` - It takes the array `arr` and a callback function. The callback is executed for each element in the array, receiving the element (`el`) and its index (`index`). **Pros and Cons:** * **`for...of`:** - **Pros:** Generally considered more concise and readable than using `_.each`. It's also often faster due to being a native JavaScript feature. - **Cons:** Requires modern JavaScript environments (ES6 or later) for full support. * **`_.each`:** - **Pros:** More flexible as it allows passing additional data (like the index) into the callback function. - **Cons:** Adds a dependency on Lodash, which increases the size of your project and potential for conflicts. **Other Considerations:** - **Benchmark Results:** The results show that `for...of` is significantly faster than `_.each` in this case. This highlights how native JavaScript constructs can often outperform third-party libraries for simple tasks. - **Alternatives:** There are other ways to iterate over arrays besides `for...of` and `_.each`, such as traditional `for` loops or `forEach`. However, `for...of` is usually the most efficient and modern choice for simple iterations. Let me know if you'd like a deeper dive into any specific aspect or have more benchmarks to analyze!
Related benchmarks:
Native vs Lodash.js contains
Lodash.js vs Native isArrary
Lodash.js vs Native _.min
Test native unique
Comments
Confirm delete:
Do you really want to delete benchmark?