// Declaring our Animal object
var Animal = function () {
this.name = 'unknown';
this.getName = function () {
return this.name;
}
return this;
};
// Declaring our Dog object
var Dog = function () {
// A private variable here
var private = 42;
// overriding the name
this.name = "Bello";
// Implementing ".bark()"
this.bark = function () {
return 'MEOW';
}
return this;
};
// Dog extends animal
Dog.prototype = new Animal();
// Creating an instance of Dog.
var obj = new Dog();
function iterateA() {
var ret = "";
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) {
ret += obj[prop];
}
}
return ret;
}
function iterateB() {
var ret = "";
Object.keys(obj).forEach(function (prop) {
ret += obj[prop];
});
return ret;
}
function iterateC() {
var ret = "";
for (var i = 0, keys = Object.keys(obj); i < keys.length; i++) {
ret += obj[i];
}
return ret;
}
function iterateD() {
var ret = "";
for (var keys = Object.keys(obj), len = keys.length, i = 0; i < len; i++) {
ret += obj[i];
}
return ret;
}
var tmp = iterateA();
var tmp = iterateB();
var tmp = iterateC();
var tmp = iterateD();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
A | |
B | |
C | |
D |
Test name | Executions per second |
---|---|
A | 2406405.2 Ops/sec |
B | 3221296.2 Ops/sec |
C | 4528368.5 Ops/sec |
D | 4542309.0 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance of different approaches to iterate over an object's properties in JavaScript. The test cases use two objects, Animal
and Dog
, which are created using the function
keyword.
Object.keys() vs for-in hasOwnProperty
The benchmark compares the performance of three methods:
hasOwnProperty()
to filter out inherited properties).Object.keys()
function to get an array of the object's property names, and then iterates over that array using forEach()
.iterateC()
and iterateD()
, which use traditional for
loops with Object.keys()
and indexing into the array, respectively.Options Comparison
Here's a brief summary of each option:
Object.keys()
if the object has many inherited properties.forEach()
can be slower than traditional for
loops due to its overhead.iterateC()
: Uses indexing into the Object.keys()
array, which can lead to slower performance due to the need to calculate the array length and bounds.iterateD()
: Similar to iterateC()
, but uses a more concise syntax by calculating the array length and loop bounds directly.Pros and Cons
Library Usage
None of the test cases explicitly use a library or external dependency.
Special JS Features/Syntax
The benchmark uses JavaScript features like function
declarations, object creation, property names, and array iteration methods. However, these are standard JavaScript features and do not require special knowledge or expertise to understand.
Alternatives
If you were to rewrite this benchmark, you might consider additional alternatives, such as: