<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
var params = [ "hello", true, 7 ];
var index = 0;
params.forEach(param => index++);
var params = [ "hello", true, 7 ];
var index = 0;
_.each(params, param => index++);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.forEach | |
lodash each |
Test name | Executions per second |
---|---|
Array.prototype.forEach | 103297760.0 Ops/sec |
lodash each | 9193175.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
What is being tested?
The benchmark compares two approaches to iterate over an array:
Array.prototype.forEach
(built-in JavaScript method)_
.each (method from the Lodash library)The test uses a simple example with three elements in the array: "hello"
, true
, and 7
.
Options compared
Two options are being compared:
Array.prototype.forEach
_
.eachPros and Cons of each approach:
Built-in JavaScript (Array.prototype.forEach)
Pros:
Cons:
Lodash library (_).each
Pros:
forEach
methodCons:
Library (Lodash) purpose
The Lodash library is a popular JavaScript utility belt that provides a wide range of functions and methods for various tasks, such as:
_.each
, forEach
)map
, filter
, reduce
)toString
, parseInt
)assign
, merge
)Special JS feature or syntax
There are no special JavaScript features or syntax mentioned in this benchmark. The code uses standard JavaScript syntax and the Lodash library's method name.
Other alternatives
If you're looking for alternative methods to iterate over an array, some other options include:
for
loop: a traditional loop that uses an index variableArray.prototype.map()
: a method that creates a new array with transformed elements (not suitable for modifying the original array)Array.prototype.reduce()
: a method that applies a function to each element in the array and accumulates a resultKeep in mind that the choice of iteration method depends on your specific use case, performance requirements, and personal preference.