var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i] = Date.now();
}
array.forEach(function(i) {
array[i] = Date.now();
});
for (var i of array) {
array[i] = Date.now();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of |
Test name | Executions per second |
---|---|
for | 268602.2 Ops/sec |
foreach | 109188.0 Ops/sec |
for..of | 108493.5 Ops/sec |
The provided benchmark tests compare the performance of three different looping constructs in JavaScript: the traditional for
loop, the Array.prototype.forEach
method, and the for..of
loop. The goal is to evaluate the execution speed of each method when populating an array with the current timestamp using Date.now()
.
Traditional for
Loop
for (var i = 0; i < array.length; i++) { array[i] = Date.now(); }
i
).Array.prototype.forEach
array.forEach(function(i) { array[i] = Date.now(); });
for
loop, as it adds the overhead of a function call for each element.break
or continue
to exit the loop prematurely.for..of Loop
for (var i of array) { array[i] = Date.now(); }
for
loop, as it involves more abstraction.The benchmark results indicate how many executions per second each looping method was able to achieve. Here are some observations:
for
loop performed significantly better, achieving 365,017 executions per second.for..of
loop had 218,646 executions per second.forEach
method had the slowest performance with 217,259 executions per second.When selecting between these options, the choice may depend on the specific use case:
for
loop may be the best choice.forEach
or for..of
could be preferable.Other alternatives to consider for iterating over arrays in JavaScript include:
array.map(func)
may be a good alternative if there's a need to transform each element.array.filter(func)
can be useful to create a new array with elements that pass a certain condition.array.reduce(func, initialValue)
can accumulate results based on the array's contents.When using these methods, it's essential to weigh performance against readability and maintainability according to the specific project requirements.