var arr = [],
LoopFunctionHandle = { halt: false };
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item)
{
if (!LoopFunctionHandle.halt)
{
someFn(item);
}
});
for (var i = 0, len = arr.length; i < len; i++)
{
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for |
Test name | Executions per second |
---|---|
foreach | 4500.8 Ops/sec |
for | 5771.1 Ops/sec |
Let's dive into the provided benchmark definition and test cases.
Benchmark Definition
The benchmark definition is a JSON object that describes the test case. It contains two main parts:
arr
and defines a function someFn
that takes an integer as input and returns its triple multiplied by 8.The script preparation code is executed before running the test cases.
Test Cases
There are two test cases:
forEach
method to iterate over the array arr
. It calls the function someFn
for each item in the array, but only if a special variable LoopFunctionHandle.halt
is set to false
.for
loop to iterate over the array arr
. The loop iterates from 0 to the length of the array, and for each iteration, it calls the function someFn
with the current element as input.Options Compared
The two test cases compare the performance of using the forEach
method versus a traditional for
loop to iterate over an array.
Pros and Cons
Library
There is no specific library used in this benchmark definition.
Special JS Features/Syntax
None mentioned.
Now, let's look at the benchmark results:
The latest benchmark result shows the performance metrics for each test case. The key values are:
In this case, the "for" loop test case performs approximately 4500 executions per second on Chrome 95 on a Desktop with Windows operating system. The "foreach" loop test case performs around 5771 executions per second under the same conditions.
Alternatives
If you're looking for alternative ways to compare performance or optimize array iteration, here are some options:
map()
and reduce()
methods instead of forEach
or for
loops.Keep in mind that the best approach will depend on your specific use case, dataset size, and performance requirements.