<script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js'></script>
var values = [{a: 30310}, {b: 100303}, {c: 3040494}]
var count = 0;
_.forEach(values, function(value) {
if (value.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 |
---|---|
Underscore.js _forEach() | |
native for loop |
Test name | Executions per second |
---|---|
Underscore.js _forEach() | 24646238.0 Ops/sec |
native for loop | 46553880.0 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being tested?
The test case compares the performance of two approaches: using Underscore.js _forEach()
and a native for
loop on large arrays. Specifically, it tests how many times the code executes the condition inside the loop (in this case, value.a != null
) for each value in the array.
Options compared
The two options being compared are:
_forEach()
: A function from the popular utility library Underscore.js that iterates over arrays and objects.for
loop: A basic looping construct in JavaScript that uses an index variable to iterate over array elements.Pros and cons of each approach
Underscore.js _forEach()
Pros:
Cons:
_forEach()
function on each elementNative for
loop
Pros:
Cons:
Library: Underscore.js
Underscore.js is a popular utility library that provides various functions for functional programming, data manipulation, and more. The _forEach()
function is one of its most commonly used methods, allowing you to iterate over arrays and objects in a concise way.
Special JS feature/syntax
There are no special JavaScript features or syntax mentioned in this benchmark.
Now, let's take a look at the individual test cases:
_forEach()
: This code uses Underscore.js _forEach()
to iterate over the values
array and increment a counter for each element where value.a != null
.for
loop: This code uses a traditional for
loop to iterate over the values
array, incrementing a counter for each element where value.a != null
.Other alternatives
For large-scale iterations, other approaches you might consider include:
Array.prototype.forEach()
or for...of
However, for most use cases, the choice between _forEach()
and a native for
loop ultimately depends on personal preference, project requirements, and performance considerations.