<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(key); }
return t;
}
function extractValuesNumver(obj) {
const t = [];
for(var key in obj) { t.push(Number(key)); }
return t;
}
var a = { 1: 1, 2: 2, 3: 3};
Object.values(a);
var a = { 1: 1, 2: 2, 3: 3};
_.values(a);
var a = { 1: 1, 2: 2, 3: 3};
extractValues(a);
var a = { 1: 1, 2: 2, 3: 3};
extractValuesNumver(a);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.values(obj) | |
_.values(obj) | |
for...in | |
for...in number |
Test name | Executions per second |
---|---|
Object.values(obj) | 1835656.4 Ops/sec |
_.values(obj) | 1327908.9 Ops/sec |
for...in | 1571272.6 Ops/sec |
for...in number | 658470.8 Ops/sec |
Let's break down the benchmark and its components.
Benchmark Definition
The benchmark is designed to compare the performance of three different approaches to extract values from an object:
Object.values(obj)
: A native JavaScript function that returns an array of values from an object._values()
(Lodash): A function from the popular utility library Lodash, which provides a more convenient way to achieve the same result as Object.values()
.for...in
loop: A traditional approach using a loop to iterate over the keys of the object and push them into an array.Options Compared
The benchmark compares the performance of these three approaches:
Object.values(obj)
vs _values()
(Lodash)Object.values(obj)
vs for...in
Object.values(obj)
vs for...in
with numeric valuesPros and Cons of Each Approach
Object.values(obj)
:_values()
:for...in
loop:Object.values(obj)
due to the overhead of iteration.Library Used
In this benchmark, Lodash is used as a library to provide the _values()
function. Lodash is a popular utility library that provides many useful functions for tasks such as data manipulation, string manipulation, and more.
Special JS Features or Syntax
None mentioned in the provided code snippet, but it's worth noting that the use of for...in
loop may require special handling for objects with non-enumerable properties (e.g., symbols). However, this is not explicitly handled in the benchmark code.
Other Alternatives
If you need to extract values from an object, other alternatives to these approaches include:
Object.keys()
and map()
functions: Object.keys(obj).map(key => obj[key])
In summary, this benchmark compares the performance of three approaches to extract values from an object: native JavaScript functions (Object.values()
), Lodash function (_values()
), and a traditional for...in
loop. Each approach has its pros and cons, and understanding these trade-offs can help you choose the best solution for your specific use case.