<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>
var array = ['a', 'b', 'c']
_.each(array, (value, index) => {
console.log(value)
})
array.forEach((value, index) => {
console.log(value)
})
array.map((value, index) => {
console.log(value)
})
for (const value of array) {
console.log(value)
}
for (let i = 0; i < array.length; i++) {
console.log(array[i])
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.each | |
forEach | |
map | |
for..of | |
for loop |
Test name | Executions per second |
---|---|
_.each | 122271.7 Ops/sec |
forEach | 126800.3 Ops/sec |
map | 129714.6 Ops/sec |
for..of | 140315.2 Ops/sec |
for loop | 155432.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, the different approaches compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark is designed to compare the performance of six different ways to iterate over an array:
_.each
from the Lodash libraryarray.forEach
array.map
for..of
loopfor
loopScript Preparation Code and Html Preparation Code
The script preparation code creates a sample array array = ['a', 'b', 'c']
. The HTML preparation code includes the Lodash library (lodash.core.js
) from a CDN.
Test Cases
Each test case represents one of the six iteration methods:
_.each
forEach
map
for..of
for
looparray.forEach
What's being tested?
The benchmark is testing the performance of each iteration method on a sample array. The goal is to determine which method is the fastest and most efficient.
Options Compared
Here's a brief overview of each option:
for
loop syntax.for
loop: A classic loop construct that iterates over an array using an index variable.Pros and Cons
Here's a summary of the pros and cons of each option:
Option | Pros | Cons |
---|---|---|
_.each | Convenient, easy to use (nested data structures) | Overhead due to callback function |
forEach | Fast, efficient | Limited to iterating over arrays |
map | Versatile (iteration and transformation), fast | Overhead due to array creation |
for..of | Fast, efficient, modern syntax | Only available in modern browsers/Node.js |
traditional for loop |
Fast, efficient, minimal overhead | Verbose, difficult to read |
Other Considerations
_.each
is a convenient option for working with nested data structures, but may have performance implications due to the callback function.forEach
and map
can be used for both iteration and transformation, making them more versatile than traditional loops.for..of
is a modern and efficient loop construct, but its availability depends on the browser or environment.Alternatives
Other alternatives to these options include:
filter()
, reduce()
, and other array methods in combination with forEach
or map
These are just a few examples, and the best approach will depend on the specific requirements of your project.