var arr = ['hello', 'a', 'b'];
let val;
for(i=0; i<arr.length; i++){
var value = arr[i];
if (value === 'b') {
val = value;
break;
}
}
var arr = ['hello', 'a', 'b'];
let val;
for (var value of arr) {
if (value === 'b') {
val = value;
break;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for test | |
for of test |
Test name | Executions per second |
---|---|
for test | 153917888.0 Ops/sec |
for of test | 154032432.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
MeasureThat.net is comparing the performance of two approaches for iterating over arrays in JavaScript: traditional for
loops and the new for...of
syntax.
The benchmark is testing which approach is faster when searching for a specific value ('b'
) within an array. The test case uses a fixed-size array with three elements: 'hello'
, 'a'
, and 'b'
.
Options compared
There are two options being compared:
for
loop: This involves using a traditional for
loop to iterate over the array, incrementing an index variable (i
) until it reaches the length of the array.for...of
syntax: This is a new way of iterating over arrays introduced in ECMAScript 2015 (ES6). It uses a for...of
loop with a valueOf()
method to extract each element from the array.Pros and cons
for
loop:for...of
, more verbose.for...of
syntax:Library usage
In this benchmark, there is no explicit library usage mentioned. However, the for...of
syntax relies on the built-in Array.prototype.forEach()
method, which is a part of the ECMAScript standard and therefore not considered a external library.
Special JS features or syntax
The benchmark uses the new for...of
syntax, which was introduced in ES6. This means that users who are familiar with this feature will be able to run this benchmark easily.
Other alternatives
If you're interested in running alternative benchmarks, here are some common options:
for
loop or a while loop.indexOf()
, findIndex()
, or every()
might be faster for certain use cases.map()
, filter()
, or reduce()
can provide different performance characteristics.Keep in mind that benchmarking JavaScript performance is a complex topic, and the results may vary depending on the specific use case, platform, and version of JavaScript being used.