var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
let sum = 0;
for (var i = 0, len = array.length; i < len; i++) {
sum += array[i];
}
let sum = 0;
for (var item in array) {
sum += item;
}
let sum = 0;
array.forEach(function(item, index) {
sum += item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for each | |
forEach |
Test name | Executions per second |
---|---|
for | 1631.6 Ops/sec |
for each | 3428.4 Ops/sec |
forEach | 25386.4 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is designed to measure the performance of three different ways to calculate the sum of an array:
for
loopfor each
loop (also known as iterating over an object's properties)forEach
methodThese three approaches are being compared to determine which one is the most efficient.
Script Preparation Code
The script preparation code generates a large array of 10,000 elements and initializes its values from 0 to 9,999 using a for
loop.
var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
This code sets up the input data for the benchmark.
Html Preparation Code
There is no HTML preparation code provided, which means that this benchmark only tests the JavaScript engine's performance and does not take into account any browser-specific rendering or layout-related factors.
Library Usage
None of the benchmark test cases use any external libraries. The tests are designed to isolate the JavaScript engine's performance.
Special JS Features or Syntax
The forEach
method is a built-in JavaScript function that was introduced in ECMAScript 5 (ES5). It allows iterating over an array without having to manually keep track of indices. However, this feature requires support for ES5 or later.
Benchmark Results
The latest benchmark results show the performance metrics for each test case:
forEach
: approximately 25,386 executions per secondfor each
: approximately 3,428 executions per secondfor
: approximately 1,631 executions per secondAs you can see, the forEach
method outperforms both the for each
and for
loops.
Pros and Cons of Different Approaches
Here's a brief summary of the pros and cons of each approach:
for
loop:for each
loop (iterating over an object's properties):forEach
method.forEach
method:Other Alternatives
If you need to calculate the sum of an array without using a loop, you could consider using:
reduce()
method: This is another built-in method that can be used to accumulate values in an array. While it's a more modern alternative to loops, its performance might not be as good as the optimized forEach
method.Keep in mind that these alternatives will add overhead due to their external dependencies, making them less suitable for performance-critical code.