var testArray = [];
for (var i = 1; i <= 100; i++) {
testArray.push(i);
}
for(var i = 0, length = testArray.length; i < length; i += 1) {
console.log(testArray[i]);
}
var testArray = [];
for (var i = 1; i <= 100; i++) {
testArray.push(i);
}
testArray.forEach((item) => {
console.log(item);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
forEach |
Test name | Executions per second |
---|---|
for loop | 1531.0 Ops/sec |
forEach | 705.1 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing two approaches: for
loop and forEach
method (also known as Array.prototype.forEach() in JavaScript). The test cases create an array of numbers from 1 to 100, perform some operations on it, and then log each element to the console using either a for
loop or the forEach
method.
Options Compared
Two options are being compared:
for
Loop: A traditional loop that uses a counter variable (i
) to iterate over the array elements.forEach
Method: A built-in method that iterates over an array and executes a callback function for each element.Pros and Cons of Each Approach
for
LoopPros:
for
loops can be faster than forEach
methods because they avoid the overhead of function calls and don't require creating an iterator object.for
loop, you have more control over the iteration process, such as incrementing the counter variable.Cons:
for
loop can be more verbose than using the forEach
method.for
loop may throw errors.forEach
MethodPros:
forEach
method is a concise way to iterate over an array and perform operations on each element.forEach
method automatically skips null or undefined values in the array.Cons:
forEach
method can introduce some performance overhead due to function call overhead.forEach
method, you have less control over the iteration process than with a for
loop.Library and Special JS Features
There are no libraries mentioned in this benchmark. However, if we were to use other JavaScript features, we might consider:
Other Considerations
When writing benchmarks like this one, it's essential to consider the following factors:
Alternatives
If you're interested in exploring alternative approaches, consider the following options:
Keep in mind that the choice of approach depends on your specific requirements, performance constraints, and personal preferences.