let operation = [{foo: {bar: 'bar'}},{foo: {bar: 'bar'}},{foo: {bar: 'bar'}},{foo: {bar: 'bar'}}];
for (let i=0; i<operation.length; i++) {
if (operation[i].foo && operation[i].foo.bar) {
console.log(operation[i].foo.bar);
}
}
let operation = [{foo: {bar: 'bar'}},{foo: {bar: 'bar'}},{foo: {bar: 'bar'}},{foo: {bar: 'bar'}}];
for(let value of operation){
if (value.foo && value.foo.bar) {
console.log(value.foo.bar);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
for...of loop |
Test name | Executions per second |
---|---|
for loop | 37008.9 Ops/sec |
for...of loop | 32090.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The provided JSON represents a benchmark definition, which outlines the test to be performed. In this case, we have two test cases:
These test cases aim to compare the performance of using a traditional for
loop versus the more modern and concise for...of
loop.
What is tested?
The benchmark tests how many times each loop type can execute in a given amount of time. The specific task for each test case is:
operation
containing four objects with nested properties.for
loop, checking if each object has a property foo
and another property bar
.bar
to the console for each matching object.operation
containing four objects with nested properties.for...of
loop, checking if each object has a property foo
and another property bar
.bar
to the console for each matching object.Options compared
The two test cases are:
for
loopfor...of
loopThese loops differ in how they access and process elements in the array:
for
loop:i
) to iterate through the array.i++
) at the end of each iteration.for...of
loop:value
in this case).Pros and Cons
Here's a brief summary of the pros and cons of each loop type:
Traditional for
loop:
Pros:
Cons:
Modern for...of
loop:
Pros:
Cons:
Library usage
There is no explicit library mentioned in the benchmark definition. However, it's likely that MeasureThat.net uses a standardized JavaScript environment to run these tests, ensuring consistency across different browsers and devices.
Special JS features or syntax
The for...of
loop introduced in ECMAScript 2015 (ES6) provides a more concise and modern way of iterating over arrays. This feature is widely supported in modern JavaScript environments, including web browsers and Node.js.
Alternatives
If you're interested in exploring alternative loop types or optimization techniques for your own JavaScript projects, consider the following:
while
loops: Can be useful when dealing with dynamic array lengths or complex iteration logic.Array.prototype.forEach()
: A more concise way to iterate over arrays without using for
loops. However, it can have performance implications in certain cases.Keep in mind that these alternatives might not be directly comparable to the traditional for
loop and modern for...of
loop in this benchmark.