<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var values = [{a: 30310}, {b: 100303}, {c: 3040494}]
var count = 0;
values.forEach(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++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.forEach | |
native |
Test name | Executions per second |
---|---|
Array.forEach | 8264871.5 Ops/sec |
native | 1944108.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: using Array.forEach()
and a traditional for
loop with an index variable (i
). The test case uses the Lodash library for array operations.
What's Being Tested?
The main differences between the two approaches are:
forEach()
is designed to iterate over an array, while a traditional for
loop requires manual incrementing of an index variable.forEach()
uses a callback function, whereas the traditional for
loop uses an explicit iteration with an index variable.Options Compared
The two options being compared are:
Array.forEach()
:for
loop with index variable (i
):forEach()
since it avoids function call overhead.Library and Syntax Considerations
The Lodash library is used for array operations in the benchmark. Specifically, the forEach()
method is used to iterate over the values
array.
There are no special JavaScript features or syntaxes being tested in this benchmark.
Alternative Approaches
Other alternatives could include:
Array.prototype.forEach.call()
: This approach uses a similar callback function as Array.forEach()
, but with the explicit call to forEach()
on the prototype of the values
array.reduce()
or map()
: Instead of using forEach()
, one could use reduce()
or map()
to iterate over the array, which might have different performance characteristics.Benchmark Preparation Code
The script preparation code sets up an example dataset (values
) and includes a reference to the Lodash library. The HTML preparation code loads the Lodash library from a CDN.
Individual Test Cases
Each test case has a unique Benchmark Definition
that defines the loop or function to be tested. In this case, there are two test cases:
Array.forEach()
: Iterates over the values
array using the forEach()
method.for
loop with index variable (i
): Iterates over the values
array using a traditional for
loop.The test results show the execution frequency per second for each browser, providing insight into performance differences between the two approaches.