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 |
---|---|
keys | |
getOwnPropertyNames | |
for ... in |
Test name | Executions per second |
---|---|
keys | 32769372.0 Ops/sec |
getOwnPropertyNames | 38497428.0 Ops/sec |
for ... in | 61259712.0 Ops/sec |
Benchmark Overview
The provided benchmark, hosted on MeasureThat.net, compares the performance of three approaches to iterate over the properties of an object:
for...in
Object.getOwnPropertyNames()
Object.keys()
(with a custom filter)Approach 1: for...in
The for...in
loop iterates over the object's property names, including inherited ones. This approach is not recommended for performance-critical code because it can be slower due to the following reasons:
Pros:
Cons:
Approach 2: Object.getOwnPropertyNames()
This method returns an array containing all property names, including non-enumerable ones. The use of this approach is generally discouraged in modern JavaScript development due to its potential performance impact and less predictable behavior compared to other methods:
Pros:
Cons:
for...in
.Approach 3: Object.keys()
with custom filter
This approach uses Object.keys()
to get an array of property names and then applies a custom filter to exclude properties starting with $
. The use of this approach provides better performance due to the optimized filtering:
Pros:
Object.getOwnPropertyNames()
.Cons:
Library Usage
In this benchmark, the obj
object is defined using a template string, which includes special characters like $
. The use of these characters in the benchmark suggests that MeasureThat.net supports running JavaScript tests with custom properties. The library used here is not explicitly mentioned, but it's likely that the test uses a subset of the ECMAScript standard.
Special JS Feature
The benchmark uses template literals
(introduced in ECMAScript 2015) to define the obj
object. This feature allows for more readable and efficient string concatenation. The use of template literals is generally considered best practice in modern JavaScript development.
Other Alternatives
If you need to compare these approaches, you could consider using a different testing framework or benchmarking tool, such as:
These tools provide more advanced features and customization options for writing and running benchmarks.