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 = 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 | 1544487.9 Ops/sec |
Cached property names | 2499515.5 Ops/sec |
for in | 4462775.0 Ops/sec |
Measuring the performance of different approaches to iterate over an object's properties is crucial in understanding the underlying mechanics of JavaScript's for...in
loop, Object.getOwnPropertyNames()
, and accessing properties via arrays.
Options being compared:
Object.getOwnPropertyNames()
result and checking if each property name starts with a $
(indicating it's not a special property). If it does, it skips that iteration.$names
array directly to iterate over its elements, accessing the corresponding properties via bracket notation (obj[ks[i]]
).Pros and Cons of each approach:
getOwnPropertyNames()
, as it leverages the optimized array access.$names
is an array, which might not be the case for all objects.Library usage:
None of the benchmark cases explicitly use a library. However, some JavaScript engines (like V8 in Chrome) provide built-in optimizations and features that can influence performance.
Special JS feature or syntax:
There are no explicit special features or syntaxes mentioned in the benchmark definition. The $names
array is used as an array literal, which is a standard JavaScript syntax.
Other considerations:
Alternative approaches:
Some possible alternative approaches for iterating over an object's properties include:
for...in
loop with the hasOwnProperty()
method to filter out special properties.Object.keys()
method, which returns an array of property names.for...of
loops or Map
/Set
objects for iteration.However, these alternatives are not explicitly tested in this benchmark case.