<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
var arr = Array.from({ length: 10000 }).map((value, i) => i);
_.forEach(arr, function(e, i) {})
for (const e of arr) {}
for (const [i, e] of arr.entries()) {}
arr.forEach(function(e, i) {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.foreach | |
native for-of | |
native for-of + entries | |
native forEach |
Test name | Executions per second |
---|---|
lodash.foreach | 24194.7 Ops/sec |
native for-of | 170903.1 Ops/sec |
native for-of + entries | 41844.2 Ops/sec |
native forEach | 225724.6 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark measures the performance of three different approaches to iterate over an array:
lodash.foreach
(using Lodash library)for-of
loopforEach
method with callback functionEach test case uses a specific iteration approach, and the results are compared to determine which one is the fastest.
Test Case 1: lodash.foreach
foreach
function from the Lodash library iterates over an array using a callback function.Test Case 2: Native for-of
loop
for-of
loop is a built-in iteration mechanism that allows iterating over arrays using a more concise syntax.for-of
loop syntax and its limitations (e.g., no iteration over objects or arrays with non-numeric keys).Test Case 3: Native forEach
method with callback function
forEach
method is another built-in iteration mechanism that allows iterating over arrays using a callback function.for-of
loop, as it only involves array indexing and callback function execution.for-of
, as the method call overhead is still present.for-of
loop due to the need to include callback functions.Test Case 4: Native for-of + entries
for-of
loop and array's entries()
method to iterate over an array.entries()
method.for-of
.entries()
.entries()
correctly with the native for-of
loop.Other Considerations
When evaluating these alternatives, consider factors like:
In this benchmark, the results indicate that the native for-of
loop is the fastest approach for iterating over an array. However, the choice of iteration method ultimately depends on personal preference, project requirements, and familiarity with the relevant library or framework.
Alternatives
Other alternatives to consider when iterating over arrays in JavaScript include:
for
loop with explicit indexing (e.g., arr[i] = value; i++
)map()
method for transformationsKeep in mind that the performance characteristics and trade-offs of each approach can vary depending on specific use cases and requirements.