<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;
_.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++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 28932542.0 Ops/sec |
native | 49332832.0 Ops/sec |
I'd be happy to explain the JavaScript benchmark and its various components.
Benchmark Overview
MeasureThat.net is a website that allows users to create and run microbenchmarks in JavaScript. The goal of these benchmarks is to compare the performance of different approaches to achieve a specific task, such as iterating over an array of objects.
Script Preparation Code
The script preparation code is a snippet of JavaScript that sets up the environment for the benchmark:
var values = [{a: 30310}, {b: 100303}, {c: 3040494}];
This code creates an array values
with three objects, each containing a property a
. The purpose of this script is to provide a fixed dataset that will be used in the benchmark.
Html Preparation Code
The HTML preparation code includes a reference to the Lodash library:
<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
Lodash (a popular utility library for JavaScript) provides various functions that can be used in the benchmark, including forEach
.
Individual Test Cases
There are two test cases:
forEach
: This test case uses the Lodash forEach
function to iterate over the values
array:_.forEach(values, function(v,i) {
if (v.a != null) {
count++;
}
})
The purpose of this test is to measure the performance of using the Lodash forEach
function.
for
loop: This test case uses a traditional for
loop to iterate over the values
array:for (var i = 0; i < values.length; i++) {
if (values[i].a != null) {
count++;
}
}
The purpose of this test is to measure the performance of using a traditional for
loop.
Benchmark Results
The latest benchmark results show two tests running in Chrome 128 on a desktop with Windows:
forEach
: This test case executed approximately 7,620,873 times per second.for
loop: This test case executed approximately 4,430,573 times per second.Library: Lodash
Lodash is a popular utility library for JavaScript that provides various functions for tasks such as string manipulation, array manipulation, and more. In this benchmark, Lodash's forEach
function is used to iterate over the values
array.
Special JS Feature/ Syntax: None mentioned in this explanation.
Other Alternatives
If you wanted to test alternative approaches to iterating over an array of objects, some other options might include:
for...in
loopwhile
loop with an index variableforEach
function)Keep in mind that the performance of these alternatives may vary depending on the specific use case and JavaScript environment.