<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++;
}
}
var count = 0;
var i = -1;
while (++i < values.length) {
if (values[i].a != null) {
count++;
}
}
var count = 0;
values.forEach(function(v,i) {
if (v.a != null) {
count++;
}
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach() | |
native for() | |
native while() | |
native forEach() |
Test name | Executions per second |
---|---|
lodash.forEach() | 3485232.2 Ops/sec |
native for() | 1999319.8 Ops/sec |
native while() | 2001905.1 Ops/sec |
native forEach() | 11008980.0 Ops/sec |
The provided JSON represents a benchmark test case on MeasureThat.net, comparing the performance of three different iteration methods in JavaScript: for
, while
, and forEach
. The tests are designed to measure how efficiently each method can iterate over an array and perform a simple condition check.
Here's a breakdown of each option:
1. Lodash forEach()
_
(underscore) is a popular utility library for JavaScript that provides functional programming helpers, including the forEach
function.forEach
method is a well-known and widely used function in the JavaScript community, making it easy for developers to understand and implement.forEach
provides good performance.2. Native for
loop
for
loop is a fundamental construct in JavaScript for iterating over arrays and objects.forEach
, a traditional for
loop requires more code and might be less readable.3. Native while
loop
while
loop can be used for iteration, especially when the size of the array is not known in advance.while
loop is straightforward, making it accessible to developers who are new to iteration.while
loop can lead to slower execution compared to other methods like forEach
or for
.Other alternatives
Other iteration methods not included in this benchmark include:
for...of
and for...in
: These are used for iterating over arrays and objects, respectively. They provide a more modern and concise alternative to traditional for
loops but have slightly different syntax.every
, some
, or find
: These functions can be used for iteration but typically perform specific operations (e.g., checking if all elements meet a condition) rather than counting.In this specific benchmark, the focus is on comparing the performance of basic iteration methods (for
, while
, and forEach
). The inclusion of Lodash's forEach
highlights the advantages of using optimized implementations for common functions.