<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.6/underscore-umd-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 |
---|---|
Underscore.js _forEach() | |
native for loop |
Test name | Executions per second |
---|---|
Underscore.js _forEach() | 3701671.8 Ops/sec |
native for loop | 2152559.2 Ops/sec |
Let's break down the benchmark and its results.
Benchmark Definition
The benchmark compares the performance of two approaches:
_forEach()
: This test uses the _.forEach
function from the Underscore.js library to iterate over an array of objects. The purpose of this function is to execute a callback function once for each element in the array.Options Compared
The benchmark compares two options:
_forEach()
functionPros and Cons of Each Approach
_forEach()
:Library: Underscore.js
Underscore.js is a popular JavaScript utility library that provides various functional programming helpers. The _forEach
function is one of its most commonly used functions, allowing developers to iterate over arrays and execute callback functions for each element.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax mentioned in this benchmark. Both tests use standard JavaScript features (loops) and do not rely on any experimental or deprecated syntax.
Other Alternatives
If you need to compare performance of other array iteration methods, consider the following alternatives:
Array.prototype.forEach()
: This method is similar to Underscore.js _forEach()
, but it's a built-in JavaScript function.Array.prototype.map()
and Array.prototype.filter()
: These methods are also part of the Array prototype and can be used for array iteration, but they may have different performance characteristics compared to native for loops or _forEach()
.for...of
Loop: This is a newer type of loop that's more concise and readable than traditional for loops. However, its performance characteristics may vary depending on the browser implementation.In summary, this benchmark compares two common approaches for iterating over arrays in JavaScript: using the Underscore.js _forEach()
function versus a native for loop. The results indicate that the native for loop approach is generally faster than using _forEach()
, but both approaches have their own trade-offs in terms of code readability and maintainability.