var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1
};
for (var i=10000; i > 0; i--) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(key);
}
}
}
for (var i=10000; i > 0; i--) {
Object.keys(obj).forEach(key => console.log(key));
}
for (var i=10000; i > 0; i--) {
for (var key in obj) {
console.log(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in hasOwnProperty | |
Object.keys | |
for-in |
Test name | Executions per second |
---|---|
for-in hasOwnProperty | 3.3 Ops/sec |
Object.keys | 3.1 Ops/sec |
for-in | 4.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Overview
The test measures the performance of three different approaches to iterate over an object's keys:
for-in
with hasOwnProperty
Object.keys()
for-in
What's being tested?
Each test case is designed to run 10,000 iterations using a predefined object (obj
) with six properties. The tests compare the execution time of each approach:
for-in hasOwnProperty
: Uses the hasOwnProperty()
method to filter out inherited properties and only logs the keys that are directly owned by the object.Object.keys()
: Utilizes the Object.keys()
function, which returns an array of all keys in the object. This approach is expected to be faster since it doesn't require filtering.for-in
: Iterates over all properties using the for-in
loop without any filtering or optimization.Pros and Cons
for-in hasOwnProperty
:Object.keys()
for simple cases.Object.keys()
:for-in
:Library/Library Purpose
The test uses the Object.keys()
function from the ECMAScript Standard Library. This function is a built-in method that returns an array of strings containing the property names in the specified object (in this case, obj
).
Special JS Features/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark.
Other Alternatives
If you're looking for alternative approaches to iterate over objects, consider:
in
operator and string comparison to achieve similar results.keys()
function that is equivalent to Object.keys()
.Keep in mind that these alternatives may not be optimized for performance and should be carefully evaluated based on your specific use case.