<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[t.length] = obj[key];
}
return t;
}
var a = { a: 1, b: 2, c: 3};
Object.values(a);
var a = { a: 1, b: 2, c: 3};
_.values(a);
var a = { a: 1, b: 2, c: 3};
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) | 11469841.0 Ops/sec |
_.values(obj) | 2976745.5 Ops/sec |
for-in | 23202378.0 Ops/sec |
Benchmark Explanation
The provided benchmark compares the performance of three approaches to extract values from an object:
Object.values()
: This is a built-in JavaScript method that returns an array containing all the values of an object, excluding keys._values()
: This is a utility function from the popular Lodash library that also extracts values from an object and returns them as an array.for...in
loop: The benchmark uses a custom function (extractValues
) that iterates over the object's properties using a for...in
loop, extracting each value and adding it to an array.Pros and Cons of Each Approach
Object.values()
:_values()
:for...in
loop:Library and Special JS Feature Explanation
The benchmark uses Lodash library, which is a popular utility belt that provides a wide range of functions for various tasks. In this case, _values()
is used as a convenient alternative to implementing the same functionality manually.
There are no special JavaScript features or syntax used in the benchmark.
Other Alternatives
For extracting values from an object, other alternatives could include:
Object.keys()
, which returns an array of an object's own enumerable property names. You can use this with forEach
or map
to extract values.Object.entries()
and then using Array.prototype.map
or a custom loop to extract values.Benchmark Considerations
The benchmark is designed to compare the performance of these three approaches in different browsers and devices. The test cases are relatively simple, as they only involve creating an object with some values and extracting those values using each approach. To make the benchmark more realistic, additional factors like object size, complexity, or other dependencies could be introduced.
The latest benchmark results show that:
for-in
(custom loop) is the fastest in this specific test case.Object.values()
is the second-fastest, closely followed by _values()
(Lodash).These results may vary depending on the actual use cases and scenarios where these approaches are used.