var obj = {};
for (let i = 0; i < 1000; i++) {
obj['abc_' + i] = i;
}
const keys = Object.keys(obj);
keys.forEach(function(key, value) {
console.log(obj[key]);
});
const values = Object.values(obj);
values.forEach(function(key, value) {
console.log(value);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.keys | |
Object.values |
Test name | Executions per second |
---|---|
Object.keys | 478.2 Ops/sec |
Object.values | 481.3 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance difference between two approaches to access values in an object: Object.keys
and Object.values
. The test creates an object with 1000 properties, each initialized with a unique value.
Options Compared
Two options are compared:
Pros and Cons of Each Approach
obj[key]
), which can lead to slower performance due to string lookup.Library Used (None)
No specific library is used in this benchmark. The test relies solely on built-in JavaScript features.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes explicitly mentioned or utilized in the provided code.
Other Alternatives
If you needed to access object properties, some other alternatives could be considered:
for...in
loop directly on the object (similar to using Object.keys
but potentially slower due to string lookup): for (var key in obj) { console.log(obj[key]); }
Object.entries()
or Array.from()
: Object.entries(obj).forEach(([key, value]) => { console.log(value); });
However, for simple access cases with direct values, using Object.values
is still the recommended approach due to its performance benefits.
Benchmark Preparation Code Analysis
The provided preparation code creates an object (obj
) and populates it with 1000 properties. The script then uses a loop to iterate over these properties, assigning each property a unique value between 0 and 999.
Individual Test Cases Analysis
Two test cases are defined:
Object.keys()
to get an array of keys from the object and then iterates through this array using a forEach
callback function to log the corresponding values.Object.values()
to get an array of values from the object, iterating over it with another forEach
callback function to log each value.These test cases are intended to compare the performance and behavior of these two approaches in a simple scenario.