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++;
}
let n = 0;
for (const k in obj) {
if (k.charAt(0) == '$') continue;
n++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getOwnPropertyNames | |
for ... in |
Test name | Executions per second |
---|---|
getOwnPropertyNames | 33878768.0 Ops/sec |
for ... in | 64689564.0 Ops/sec |
Let's break down the benchmark and its test cases.
What is being tested?
The benchmark is comparing two approaches to iterate over an object's property names:
getOwnPropertyNames
(also known as the "object property iterator" in ECMAScript): This method returns a static view of an object's own enumerable property names.for ... in
loop: This syntax allows iterating over an object's properties, including those that are not enumerable.Options compared
The two approaches being tested are:
Object.keys()
method to get an array of property names and then iterating over it.for
loop with the in
keyword to iterate over the object's properties.Pros and cons
getOwnPropertyNames:
Pros:
Cons:
Object.keys()
), which might incur additional overhead.Object.keys()
.for ... in:
Pros:
Cons:
Library/Functionality Used
None of the test cases use any external libraries or functions besides the built-in Object.keys()
method and the JavaScript for
loop syntax.
Special JS Features/Syntax
The only special feature used in these test cases is the in
keyword in the for ... in
loop, which is a part of the traditional for
loop syntax. This keyword allows iterating over an object's properties.
Alternatives
Other alternatives for iterating over an object's property names could be:
Object.getOwnPropertyNames()
method (which returns only own enumerable and non-writable properties).However, these alternatives are not tested in this benchmark, and the results may vary depending on the specific use case and performance requirements.