<script src='https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js'></script>
var value = [{a: 30310}, {b: 100303}, {c: 3040494}, {d: 6542321}, {e: 13123531}]
_.forEach(value, function(v,i) {console.log(v)})
value.forEach(function(v,i) {console.log(v)})
for(const v of value){
console.log(v)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native | |
native forof |
Test name | Executions per second |
---|---|
lodash | 72338.3 Ops/sec |
native | 76778.9 Ops/sec |
native forof | 83368.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three approaches for iterating over an array: using the _forEach
function from the Lodash library, the foreach
method (which is not a standard JavaScript method, but rather a shorthand for Array.prototype.forEach
), and the for...of
loop with const
.
Options Compared
_forEach
: This option uses the _forEach
function from the Lodash library, which provides a higher-order function that takes an array as its first argument and a callback function as its second argument.foreach
method: This option uses the foreach
method on an array, which is not a standard JavaScript method. However, it's equivalent to calling Array.prototype.forEach
.for...of
loop with const
: This option uses a traditional for...of
loop with const
, where each iteration of the loop logs the current value.Pros and Cons
_forEach
:foreach
method: Not recommended, as it's not a standard JavaScript method and may cause confusion.for...of
loop with const
:forEach
, especially for large datasets.Library Used
In this benchmark, the Lodash library is used. Lodash provides a set of utilities that can be used to simplify tasks such as array manipulation, object merging, and more.
Special JS Feature/Syntax
The for...of
loop with const
is a relatively new feature in JavaScript (introduced in ECMAScript 2015) that allows iterating over iterable objects like arrays. It's designed to provide a more concise way of working with collections compared to traditional for
loops.
Other Alternatives
For iterating over arrays, other alternatives include:
Array.prototype.forEach()
methodwhile
loop or a do...while
loop to iterate over an arrayIn general, for simple use cases, using the native forEach
method or a traditional for
loop may be sufficient. However, when working with large datasets or complex logic, libraries like Lodash or Underscore.js can provide valuable assistance in simplifying code and improving performance.