var array = new Array(100);
for (let i = 0; i < array.length; i++) {
array[i] = 0;
}
array[50] = 1;
let isOne = false;
for (var i = 0; i < array.length; i++) {
if (array[i] === 1) {
isOne = true;
break;
}
}
let isOne = false;
array.forEach(function(i) {
if (array[i] === 1) {
isOne = true;
}
});
let isOne = array.some(function(i) {
return array === 1;
});
let isOne = false;
for (var i of array) {
if (array[i] === 1) {
isOne = true;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 2517302.8 Ops/sec |
foreach | 1361929.1 Ops/sec |
some | 2194339.8 Ops/sec |
for..of | 1021862.2 Ops/sec |
Let's dive into the JavaScript microbenchmarking test case.
Overview
The test measures the performance of four different loop constructs: for
, forEach
, some
, and for...of
. The goal is to determine which construct is the most efficient for a specific use case: checking if an element in an array has a certain state (in this case, whether it's equal to 1).
Loop Constructs Compared
for
: A traditional loop that uses a counter variable and an explicit termination condition.forEach
: A method that iterates over the elements of an array, providing access to each element in its context.some
: A method that returns true
if at least one element in an array satisfies a provided testing function.for...of
: A newer loop construct that uses a for
loop with a const
or let
declaration and the of
keyword to specify the iterable.Pros and Cons of Each Approach
for
:forEach
:for
loops for large arrays.some
:for
loops due to the method invocation overhead, and its behavior is not immediately obvious to all developers.for...of
:Library Used
In this test case, none of the loops use an external library. However, the forEach
loop uses the built-in Array.prototype.forEach()
method, which is a part of the ECMAScript standard.
Special JS Feature or Syntax
None of the test cases use any special JavaScript features or syntax beyond what's mentioned above.