<script src="https://cdn.jsdelivr.net/lodash/4.17.15/lodash.min.js"></script>
var values = [{a: 30310}, {b: 100303}, {c: 3040494}]
var count = 0;
_.forEach(values, function(v,i) {
if (v.a != null) {
count++;
}
})
var count = 0;
for (var i = 0; i < values.length; i++) {
if (values[i].a != null) {
count++;
}
}
var count = 0;
values.forEach(function(v) {
if (v.a != null) {
count++;
}
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native for | |
native forEach |
Test name | Executions per second |
---|---|
lodash.forEach | 13889835.0 Ops/sec |
native for | 36407964.0 Ops/sec |
native forEach | 43297812.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Overview
The benchmark is designed to compare the performance of three different approaches:
forEach
: A popular JavaScript utility library that provides a functional programming style implementation of the forEach
method.for
loop: The built-in for
loop in JavaScript, which uses an index variable to iterate over an array.forEach
method: Another built-in JavaScript method for iterating over arrays.Options Being Compared
The options being compared are the execution time and performance of each approach when used to iterate over a sample dataset (values
) and increment a counter (count
) whenever the value has a non-null a
property. The benchmark measures the number of executions per second, which represents the frequency at which the loop iterates.
Pros and Cons
forEach
:for
loop:forEach
method:Library Used
The benchmark uses the Lodash library, which provides a functional programming style implementation of the forEach
method. The specific version used is 4.17.15.
Special JS Feature or Syntax
None mentioned in the provided code snippets.
Benchmark Preparation Code and Individual Test Cases
The preparation code creates an array (values
) with three objects containing non-null a
properties, and then uses each of the three approaches to iterate over this array, incrementing a counter. The individual test cases are:
forEach
for
loopforEach
methodLatest Benchmark Result
The latest result shows that the native forEach
method performs best, followed by the native for
loop, and then the Lodash implementation.
Alternatives
Other alternatives to compare with these approaches could be:
However, for a basic benchmark like this one, native implementations are often the most suitable options.