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) {
console.log(key);
}
}
for (var i=10000; i > 0; i--) {
Object.keys(obj).forEach(key => console.log(key));
}
for (var i = 0, keys = Object.keys(obj); i < keys.length; i++) {
console.log(keys[i])
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for in | |
object keys | |
for in object keys |
Test name | Executions per second |
---|---|
for in | 2.0 Ops/sec |
object keys | 1.1 Ops/sec |
for in object keys | 15297.4 Ops/sec |
What is being tested on MeasureThat.net?
MeasureThat.net measures the performance of JavaScript microbenchmarks, specifically in the context of iterating over object properties using different methods.
Options compared:
Three options are compared:
for-in
loop uses in
keyword to iterate over an object's own property names.Object.keys()
method returns an array of a given object's own property names, which can then be iterated using various methods such as forEach
.keys
property and iterates over it directly.Pros and Cons:
for-in
loop in some cases, as it involves creating an array of property names.Library usage:
None of the benchmark definitions explicitly use any external libraries. However, the use of Object.keys()
implies that the JavaScript engine being tested is able to provide an optimized implementation for this method.
Special JS features/syntax:
None of the benchmark definitions use any special or advanced JavaScript features such as ES6 syntax, async/await, or Web Workers. The code uses standard ECMAScript 5 syntax and should be compatible with most modern browsers.
Other alternatives:
If you want to test other iteration methods, MeasureThat.net provides a few options:
for...in
with the hasOwnProperty()
method to filter out non-enumerable properties.Object.getOwnPropertyNames()
method (not available in all browsers).Map
data structure instead of objects for iteration.You can add these alternatives by modifying the benchmark definitions and providing new test cases. Keep in mind that each alternative may have different performance characteristics, so it's essential to test them thoroughly.