var obj = {
$props : ['a','b','c'],
a:1,
b:2,
c:3
}
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++;
}
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++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getOwnPropertyNames | |
Object.keys |
Test name | Executions per second |
---|---|
getOwnPropertyNames | 4438401.5 Ops/sec |
Object.keys | 4555597.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Purpose
The benchmark compares the performance of two approaches to get an array of property names from an object: Object.keys()
and the getOwnPropertyNames
method in combination with a manual filtering process.
Options Compared
Two options are compared:
Object.keys()
: This method returns an array of a given object's own enumerable property names.getOwnPropertyNames
+ manual filtering: The getOwnPropertyNames
method returns an array of all property names, including non-enumerable ones. To filter out properties whose names start with $
, the benchmark uses a manual loop to iterate over the array and skip those properties.Pros and Cons
Object.keys()
:getOwnPropertyNames
+ manual filtering:Library
The Object.keys()
method is a built-in JavaScript method that is part of the ECMAScript standard. It's widely supported across different browsers and environments.
Special JS Feature or Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's considered "standard" by the ECMAScript standard. However, it's worth noting that getOwnPropertyNames
is a legacy method from older versions of JavaScript (pre-ES6), whereas Object.keys()
is a modern method introduced in ES5.
Other Alternatives
If you need to get an array of property names and don't mind excluding non-enumerable ones, other alternatives might include:
for...in
loop with a custom filtering process.Object.values()
and then filtering it.Keep in mind that these alternatives may have different performance characteristics, trade-offs, or requirements depending on your specific use case.