var arr = [];
for(var i=0; i < 10000; i++) {
arr.push(Math.floor(Math.random() * Math.floor(10000)));
}
var sum = 0;
for (var e of arr) {
sum += e;
}
var sum = 0;
arr.forEach(e => {sum += e;})
var sum = arr.reduce((acm, current) => acm + current);
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for of | |
forEach | |
reduce | |
for i |
Test name | Executions per second |
---|---|
for of | 158769.2 Ops/sec |
forEach | 60427.2 Ops/sec |
reduce | 91042.8 Ops/sec |
for i | 1699.4 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance of four looping methods in JavaScript:
for...of
Array.forEach
Array.reduce
for
loop with a traditional index variable (i
)Each looping method is used to calculate the sum of an array of 10,000 random integers.
Options Compared
The benchmark compares the performance of these four looping methods:
for...of
loops are concise and easy to read, but may not be as efficient as traditional loops.Array.forEach
loops iterate over the array's elements, but require an explicit callback function.Array.reduce
is a functional programming approach that reduces the array to a single value, which can be efficient for certain use cases.for
loops are straightforward and often used, but may not be as concise or expressive as other looping methods.Pros and Cons
Here's a brief summary of each looping method:
Library and Special JS Features
None of the looping methods rely on external libraries. However, some features are used:
Math.floor
is used to generate random numbers within a specific range.Array.prototype.forEach
, Array.prototype.reduce
, and Array.prototype.push
methods are used by each looping method.Test Case Explanation
Each test case uses the same script preparation code to initialize an array of 10,000 random integers. Then, each looping method is tested in isolation:
for...of
: Iterates over the array using the for...of
loop construct.Array.forEach
: Iterates over the array using the forEach
method with a callback function.Array.reduce
: Reduces the array to a single value using the reduce
method with an accumulator function.for
loop: Iterates over the array using a traditional for
loop construct.Other Alternatives
If you're interested in exploring other looping methods, consider:
Array.prototype.map
=>
)Set
or Map
data structures for more complex operationsFeel free to experiment with these alternatives and compare their performance on MeasureThat.net!