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 | 19931428.0 Ops/sec |
foreach | 12626781.0 Ops/sec |
some | 13313135.0 Ops/sec |
for..of | 1286052.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
The benchmark compares the performance of four different loop constructs: for
, foreach
, some
, and for..of
. The test case uses an array of 100 elements, which is created using the new Array(100)
syntax.
Loop constructs comparison
Here's a brief overview of each loop construct:
i
) to iterate over the array indices.forEach
method, which calls a callback function for each element in the array. The callback function receives the current element as an argument (in this case, i
).some
method, which returns true
if at least one element in the array passes a test (in this case, simply checking the element using array[i]
). The callback function is called for each element.for
loop but with some key differences.Pros and cons of each approach
Library used in the test case
In this benchmark, no external library is explicitly mentioned, but we can infer that Array.prototype.forEach
and Array.prototype.some
are being used, which are built-in methods on arrays.
Special JS feature or syntax
The for..of
loop construct uses a new syntax introduced in ECMAScript 2015 (ES6). It allows iterating over arrays and other iterable objects using a concise syntax. This is a relatively recent addition to the JavaScript language, making it more suitable for modern development.
Other alternatives
For loops are still widely used and supported, so they're not being directly compared to for..of
in this benchmark. However, if you want to explore other loop constructs, you can consider using while
loops or array methods like map
, filter
, or reduce
.
Keep in mind that these alternatives might change the focus of your comparison, as they may be more efficient or have different performance characteristics.
In summary, this benchmark provides a concise and readable way to compare the performance of four loop constructs: for
, foreach
, some
, and for..of
.