var obj = {
$names : ['a','b','c'],
a:1,
b:2,
c:3
}
var ks = Object.getOwnPropertyNames(obj);
var n = 0;
for (var i = 0; i < ks.length; i++) {
var k = obj[ks[i]];
if (k.charAt(0) == '$') continue;
n++;
}
var ks = obj['$names'];
var n = 0;
for (var i = 0; i < ks.length; i++) {
var k = obj[ks[i]];
n++;
}
var n = 0;
for (var k in obj) {
if (k.charAt(0) == '$') continue;
n++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getOwnPropertyNames | |
Cached property names | |
for in |
Test name | Executions per second |
---|---|
getOwnPropertyNames | 0.0 Ops/sec |
Cached property names | 2581982.0 Ops/sec |
for in | 4346397.5 Ops/sec |
Let's break down the benchmark and its test cases.
What is being tested?
The benchmark is designed to compare three approaches for iterating over an object's properties:
Object.getOwnPropertyNames()
: This method returns an array of strings representing the names of all properties (including inherited ones) that are directly accessible on an object.for...in
loop with filtering: This approach uses the for...in
loop to iterate over all properties of an object and skips any properties whose name starts with a dollar sign ($
).Options comparison
The three approaches have different pros and cons:
Object.getOwnPropertyNames()
:getOwnPropertyNames()
if the cached list is already available.for...in
loop with filtering:getOwnPropertyNames()
and cached property names if not optimized.The for...in
loop approach is currently the fastest, but this might change depending on the specific implementation and browser optimizations.
Library considerations
The benchmark uses the Object.getOwnPropertyNames()
method, which is a standard JavaScript method. No external libraries are required for these test cases.
Special JS features or syntax
There are no special JavaScript features or syntax used in these test cases.
Other alternatives
If you wanted to include other approaches in your benchmark, some alternative methods for iterating over an object's properties could be:
Object.keys()
(which returns only own enumerable properties) and then filtering out properties whose names start with a dollar sign.for...in
, for...of
(if supported), or other iteration methods.Keep in mind that each alternative method has its pros and cons, and the best choice depends on your specific use case and requirements.