var obj = {
$props : ['a','b','c'],
a:1,
b:2,
c:3
}
const arr = Object.keys(obj);
let n = 0;
for (let i = 0; i < arr.length; i++) {
const k = arr[i];
if (k.charAt(0) == '$') continue;
n++;
}
const arr = Object.getOwnPropertyNames(obj);
let n = 0;
for (let i = 0; i < arr.length; i++) {
const k = arr[i];
if (k.charAt(0) == '$') continue;
n++;
}
let n = 0;
for (const k in obj) {
if (k.charAt(0) == '$') continue;
n++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.keys() | |
getOwnPropertyNames() | |
for ... in loop |
Test name | Executions per second |
---|---|
Object.keys() | 9906305.0 Ops/sec |
getOwnPropertyNames() | 9410627.0 Ops/sec |
for ... in loop | 26696090.0 Ops/sec |
Let's break down the benchmark test case.
Benchmark Name: getOwnPropertyNames() vs Object.keys() vs for ... in
This test compares three different ways to iterate over an object's properties:
Object.getOwnPropertyNames()
Object.keys()
for ... in
loopTest Case Descriptions
Each test case is a separate JavaScript code snippet that performs the iteration and counting of property names.
Object.keys()
to get an array of own property names, then iterates over this array using a for
loop.Object.getOwnPropertyNames()
to get an array of all property names (own and inherited), then iterates over this array using a for
loop.for ... in
loop to iterate directly over the object's properties.Library/Feature Used
None, these are built-in JavaScript features.
Pros and Cons of each approach
Object.keys()
method.Other Alternatives
There are other ways to iterate over an object's properties, such as:
forEach()
loop or a for (const key in obj) { ... }
loop without the hasOwnProperty()
check.However, these alternatives are not compared in this benchmark test case.
Benchmark Results
The latest benchmark results show:
These results indicate that the for ... in
loop is the fastest approach, likely due to its simplicity and lack of method overhead. However, it's essential to consider the trade-offs and potential use cases for each approach when choosing an iteration method.