var testObj = {}
for (let i = 0; i < 10000; i++) {
const randomString = Math.random().toString(36).substr(2, 5);
testObj[randomString] = randomString;
}
console.log(Object.keys(testObj));
console.log(Object.values(testObj));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
keys | |
values |
Test name | Executions per second |
---|---|
keys | 208.1 Ops/sec |
values | 127.8 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and considered.
Benchmark Definition
The benchmark is defined in two parts:
testObj
with 10,000 properties, each containing a random string as its value.Test Cases
There are two individual test cases:
**: This test case measures how long it takes to get an array of keys (i.e., property names) from the
testObjobject using
Object.keys()`.**: This test case measures how long it takes to get an array of values from the
testObjobject using
Object.values()`.Comparison
The benchmark compares two approaches:
Object.keys()
to retrieve the array of keys.Object.values()
to retrieve the array of values.Options Compared
These options are compared in terms of execution time, which is measured in executions per second (i.e., how many times the test can be repeated in one second).
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Object.keys()
)Object.values()
)Library and Special JS Features
In this benchmark:
Object
and Array
constructors are implicitly used in the test cases.Other Alternatives
If you wanted to modify this benchmark, here are some alternative approaches you could consider:
Object.keys()
with a for...of
loop or Array.from(Object.keys(testObj))
.Keep in mind that the performance differences between these approaches may vary depending on your specific use case and JavaScript environment.