<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)
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.each | |
forEach | |
map |
Test name | Executions per second |
---|---|
_.each | 117757.8 Ops/sec |
forEach | 124651.7 Ops/sec |
map | 125655.4 Ops/sec |
Let's dive into the explanation.
Benchmark Overview
The provided benchmark measures the performance of three different approaches to iterate over an array: _.each
(using Lodash), array.forEach
, and array.map
. The goal is to determine which approach yields the fastest execution time on a specific JavaScript engine.
Options Compared
_each
function from Lodash, a popular utility library for JavaScript. It iterates over an array using a callback function.map
returns a new array, it can be used as a way to iterate over the original array by assigning its result to a variable.Pros and Cons
Library (Lodash)
Lodash is a utility library that provides various functions for tasks such as string manipulation, object manipulation, array manipulation, and more. The _each
function is a part of Lodash's core functionality, allowing you to iterate over arrays using a callback function.
JavaScript Features
The benchmark does not explicitly use any special JavaScript features or syntax, except for the =>
syntax in the callback functions (e.g., (value, index) => { ... }
). This syntax is a shorthand way of defining arrow functions, which are a feature introduced in ECMAScript 2015 (ES6).
Other Alternatives
If you're interested in exploring alternative iteration methods or approaches to benchmarking, consider the following:
reduce
: Another native JavaScript method for array iteration.for...of
loop: A newer syntax for iterating over arrays using a more concise and readable approach.In summary, the benchmark measures the performance of three different approaches to iterate over an array: _.each (Lodash), forEach, and map. Understanding the pros and cons of each approach can help you choose the best method for your specific use case.