<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.0/underscore.js"></script>
var data = {};
Array(10000).keys().forEach(function (i) {
data[i] = i;
});
var result = 0
_.each(data, (i) => {result += i})
var result = 0
Object.values(data).forEach((i) => {result += i})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Underscore | |
Native |
Test name | Executions per second |
---|---|
Underscore | 11266.4 Ops/sec |
Native | 42062.4 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Purpose and Comparison
The benchmark is designed to compare two approaches for iterating over an object in JavaScript: using Underscore.js, a popular utility library, and the native Object.values()
method. The goal is to determine which approach is faster and more efficient.
Options Compared
The comparison involves two options:
Object.values()
method in JavaScript, which returns an array of a given object's own enumerable property values.Pros and Cons
Library Used: Underscore.js
Underscore.js is a popular utility library that provides various helper functions for tasks such as array manipulation, object iteration, and more. In this benchmark, the _.each()
method is used to iterate over the data
object.
Special JS Feature/ Syntax: None
This benchmark does not rely on any special JavaScript features or syntax beyond what's already included in modern browsers.
Other Alternatives
If you're looking for alternative approaches to iterating over objects, consider:
for...of
loop with the Symbol.iterator
method to iterate over arrays and other iterable objects.These alternatives might not be as efficient or convenient as the native Object.values()
method, but they can still provide viable solutions for specific use cases.
Keep in mind that the choice of iteration method often depends on the context and requirements of your application. Understanding the trade-offs between different approaches is essential for writing efficient and effective code.