var array = new Array(100);
for (let i = 0; i < 100; i++) {
array[i] = i * i;
}
let sum = 0
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
let sum = 0;
array.forEach(function(i) {
sum += i;
});
let sum = 0;
for (var i in array) {
sum += array[i];
}
let sum = 0;
for (var i of array) {
sum += i;
}
array.reduce((a, b) => a + b, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for in | |
for..of | |
reduce |
Test name | Executions per second |
---|---|
for | 172097.2 Ops/sec |
foreach | 6051232.0 Ops/sec |
for in | 240608.6 Ops/sec |
for..of | 8784730.0 Ops/sec |
reduce | 10205020.0 Ops/sec |
The provided JSON represents a JavaScript microbenchmark test case that compares the performance of different looping constructs: for
, forEach
, for..in
, for..of
, and reduce
. The goal is to measure which construct is the fastest for summing up elements in an array.
Looping Constructs Comparison
Here's a brief overview of each looping construct:
for
: A traditional looping construct that uses an index variable (i
) to iterate over the array.**forEach**
: An array method that calls a provided callback function for each element in the array.for..in
: A looping construct that iterates over the properties of an object (or array) using its own index variable (i
).for..of
: A looping construct that iterates over the values of an iterable (such as an array) using its own index variable (i
).reduce
: An array method that reduces the elements of an array to a single value using a callback function.Library Usage
The test case uses no external libraries. The forEach
method is a native JavaScript array method that does not require any additional library imports.
Special JS Feature or Syntax
None of the looping constructs in this test case rely on special JavaScript features or syntax, such as async/await, promises, or modern ECMAScript features like arrow functions (although some versions of forEach
might be implemented with an arrow function internally).
Benchmark Preparation Code
The preparation code generates a large array of 100 elements and populates it with values using a simple loop. This ensures that the testing environment is consistent across all looping constructs.
Alternative Loops
Other common looping constructs not included in this test case are:
while
loopsdo...while
loopsmap
, filter
, or every
Keep in mind that the performance of these alternatives might vary depending on the specific use case and JavaScript engine.
When interpreting the benchmark results, consider factors such as:
In conclusion, this benchmark highlights the importance of choosing the right looping construct for your specific use case, as different approaches may offer trade-offs between code simplicity, readability, and performance.