<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
function extractValues(obj) {
const t = [];
for(var key in obj) { t.push(obj[key]); }
return t;
}
var i;
var a = {};
for (i = 0; i < 1000; i++) {
a[i + ""] = i + "text";
}
Object.values(a);
var i;
var a = {};
for (i = 0; i < 1000; i++) {
a[i + ""] = i + "text";
}
_.values(a);
var i;
var a = {};
for (i = 0; i < 1000; i++) {
a[i + ""] = i + "text";
}
extractValues(a);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.values(obj) | |
_.values(obj) | |
for...in |
Test name | Executions per second |
---|---|
Object.values(obj) | 25393.9 Ops/sec |
_.values(obj) | 18673.3 Ops/sec |
for...in | 16724.4 Ops/sec |
I'll break down the provided benchmark JSON and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is designed to compare the performance of three approaches:
Object.values(obj)
: This method returns an array of values from the object using the values()
method..values()
: This method is part of the Lodash library, which provides a utility function for converting objects into arrays.for...in
loop: This approach uses a traditional for...in
loop to extract values from the object.Library: Lodash
The Lodash library is a JavaScript utility library that provides various functions for tasks like array manipulation, string manipulation, and object manipulation. In this benchmark, the .values()
method is used to convert an object into an array.
Special JS Feature/Syntax: for...in
loop
The manual for...in
loop approach uses a traditional JavaScript syntax to iterate over the object's properties and extract values.
Benchmark Comparison
Here's what's being compared:
Object.values(obj)
: This method is optimized by the JavaScript engine and should be the fastest..values()
: This method adds an extra layer of indirection, which may impact performance.for...in
loop: This approach requires manual iteration over the object's properties, which can lead to slower performance due to the overhead of the loop.Pros and Cons
Object.values(obj)
:.values()
:for...in
loop:Other Alternatives
If you need to extract values from an object in JavaScript, other alternatives might include:
Object.keys()
and indexing into the resulting arrayArray.from()
Keep in mind that the choice of method depends on your specific use case, performance requirements, and personal preference.