var obj = {}
var arr = []
for (var i = 0; i<100000; i++) {
var val = Math.random()
obj[i] = val
arr[i] = val
}
var wtf
function loopObj () {
for (var k in obj) {
wtf = obj[k]
}
}
function loopArr () {
for (var val of arr) {
wtf = val
}
}
console.log('prepare=> obj =', obj, '; arr =', arr)
for (var k in obj) {
wtf = obj[k]
}
for (var val of arr) {
wtf = val
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for key in object | |
for val of array |
Test name | Executions per second |
---|---|
for key in object | 35.3 Ops/sec |
for val of array | 847.7 Ops/sec |
Let's break down what's being tested on the provided JSON and explain the different approaches compared, along with their pros and cons.
Benchmark Definition:
The benchmark is comparing two approaches:
for (var k in obj) { ... }
: This approach iterates over an object using its own property names as keys.for (var val of arr) { ... }
: This approach iterates over an array using a feature called "foreach" or "for...of" loops.Comparison:
The benchmark is comparing the performance of these two approaches on a large object and an array.
Options Compared:
for (var k in obj) { ... }
)for (var val of arr) { ... }
)Pros and Cons:
Library:
None. The benchmark does not use any external libraries or frameworks.
Special JS Feature/Syntax:
The benchmark uses the "foreach" or "for...of" loop feature, which was introduced in ECMAScript 2015 (ES6). This syntax allows iterating over arrays and other iterable objects without using traditional indexing methods.
Other Considerations:
wtf
variable for no apparent reason, possibly as a placeholder or to test the effects of variable scope.Alternatives:
Other alternatives for iterating over objects and arrays include:
obj[k]
and arr[i]
)Keep in mind that the performance differences between these approaches can vary depending on the specific use case, data structure, and JavaScript engine being used.