var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
array.some(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 28518922.0 Ops/sec |
foreach | 798345.2 Ops/sec |
some | 782080.6 Ops/sec |
for..of | 519662.8 Ops/sec |
What is being tested: The provided benchmark tests the performance of four different loop constructs in JavaScript:
for
loopforEach
methodsome
methodfor...of
loop (introduced in ECMAScript 2015)These loops are used to iterate over an array and perform some operation on each element.
Options compared:
for
loop: This is the most common way of looping in JavaScript. It uses a manual index variable and increment/decrement operations.forEach
method: Introduced in ECMAScript 2009, this method allows you to iterate over an array without exposing the index variable to the caller.some
method: Also introduced in ECMAScript 2009, this method returns true
if at least one element of the array passes a test provided as a function.for...of
loop: Introduced in ECMAScript 2015, this loop is specifically designed for iterating over arrays and other iterable objects.Pros and cons:
for
loop:forEach
method:some
method:true
if at least one element passes the test.for...of
loop:for
loops or forEach
, may not work with non-array iterables.Library usage: None of the provided benchmark cases use any external libraries.
Special JavaScript feature/syntax:
The for...of
loop was introduced in ECMAScript 2015, which is a relatively recent syntax. This means that older browsers and versions of JavaScript may not support this syntax.
Benchmark preparation code:
The script prepares an array with 100 elements using the line var array = new Array(100);
.
In summary, this benchmark tests the performance of four different loop constructs in JavaScript, providing a clear comparison of their execution times. The results can be useful for developers to choose the most suitable loop construct for their specific use cases, taking into account factors like memory allocation and iteration overhead.