var testObj = {}
for (let i = 0; i < 10000; i++) {
const randomString = Math.random().toString(36).substr(2, 5);
testObj[randomString] = randomString;
}
let output;
for (const key in testObj) {
output = testObj[key];
break;
}
console.log(output);
let output;
output = Object.values(testObj)[0];
console.log(output);
let output;
output = testObj[Object.keys(testObj)[0]];
console.log(output);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for in break | |
Object keys | |
Object keys for real |
Test name | Executions per second |
---|---|
for in break | 220.8 Ops/sec |
Object keys | 65.1 Ops/sec |
Object keys for real | 255.9 Ops/sec |
Let's break down the benchmark and its various components.
Benchmark Definition
The benchmark is defined in JSON format, which represents a script that will be executed to test performance. The script preparation code creates an object testObj
with 10,000 properties, each initialized with a random string.
There are three different approaches being tested:
Object.keys()
method to get an array of the object's keys, and then accesses the first key in the array to retrieve its corresponding value.Object.keys()
result.Options compared
The three approaches are being compared to determine which one is the most efficient.
Pros and Cons
Here's a brief summary of each approach:
Object.keys()
result, which may be slower for large objects.Library
None of the approaches rely on any external libraries.
Special JS features or syntax
There is no special JavaScript feature or syntax being used in this benchmark. All three approaches use standard JavaScript syntax and features.
Other alternatives
If you wanted to test other approaches, you could consider using:
Overall, this benchmark is designed to test the performance of three different approaches to iterating over an object's keys. The results can help developers and browser maintainers optimize their JavaScript implementations for better performance.