var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1,
'h': 1,
'i': 1,
'j': 1,
'k': 1,
'l': 1,
'm': 1,
'n': 1,
'o': 1,
'p': 1,
'q': 1,
'r': 1,
's': 1,
't': 1,
'u': 1,
'v': 1,
'w': 1,
'x': 1,
'y': 1,
'z': 1,
'aa': 1,
'ba': 1,
'ca': 1,
'da': 1,
'ea': 1,
'fa': 1,
'ga': 1,
'ha': 1,
'ia': 1,
'ja': 1,
'ka': 1,
'la': 1,
'ma': 1,
'na': 1,
'oa': 1,
'pa': 1,
'qa': 1,
'ra': 1,
'sa': 1,
'ta': 1,
'ua': 1,
'va': 1,
'wa': 1,
'xa': 1,
'ya': 1,
'za': 1,
'ab': 1,
'bb': 1,
'cb': 1,
'db': 1,
'eb': 1,
'fb': 1,
'gb': 1,
'hb': 1,
'ib': 1,
'jb': 1,
'kb': 1,
'lb': 1,
'mb': 1,
'nb': 1,
'ob': 1,
'pb': 1,
'qb': 1,
'rb': 1,
'sb': 1,
'tb': 1,
'ub': 1,
'vb': 1,
'wb': 1,
'xb': 1,
'yb': 1,
'zb': 1
};
for (var i=10000; i > 0; i--) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key);
}
}
}
for (var i=10000; i > 0; i--) {
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j ++) {
console.log(keys[j]);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 0.1 Ops/sec |
Object.keys | 0.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The provided benchmark definition represents two test cases:
for-in vs object.keys with for
for-in
Object.keys
These test cases aim to compare the performance of three approaches: for-in
, object.keys
, and a combination of both (for-in
with object.keys
).
What is tested
The benchmark tests the execution speed of each approach on a large object with 32 properties, ranging from 'a' to 'za'. The test case measures how many iterations of logging the property names are executed per second.
Options compared
There are three options being compared:
for-in
loop to iterate over the object's properties. It has some limitations, as it:Object.keys()
method to get an array of property names. It is generally faster than for-in
but may still have some overhead due to string manipulation.object.keys()
, and then uses a second for-in
loop to iterate over them.Pros and Cons
Here's a brief summary of each approach:
for-in
, as it avoids the overhead of iterating over all properties.Object.keys()
.for-in
loop by retrieving property names beforehand.object.keys()
directly.Library usage
The benchmark uses no libraries, as it only involves built-in JavaScript functionality.
Special JS feature/syntax
There are no special JavaScript features or syntax used in this benchmark. The tests use standard JavaScript loops and methods.
Alternatives
If you'd like to explore alternative approaches or variations on these benchmarks, consider the following:
Object.entries()
to get an array of key-value pairs, which might offer better performance than using object.keys()
or for-in
.I hope this explanation helps you understand the JavaScript microbenchmark!