var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
let sum = 0;
let len = array.length;
for (let i = 0; i < len; i++) {
sum += 1;
}
let sum = 0;
for (let item in array) {
sum += item;
}
let sum = 0;
array.forEach(function(item, index) {
sum += item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
1 | |
2 | |
3 |
Test name | Executions per second |
---|---|
1 | 202534.0 Ops/sec |
2 | 6113.8 Ops/sec |
3 | 28481.9 Ops/sec |
Measuring JavaScript performance is crucial for understanding the efficiency of different approaches, especially when working with large datasets or complex computations.
The provided benchmark measures the execution time of three different methods to calculate the sum of an array: traditional for
loop, for...in
loop, and forEach()
method. We'll analyze each approach, their pros and cons, and discuss any special considerations.
Approach 1: Traditional for
Loop
let sum = 0;
let len = array.length;
for (let i = 0; i < len; i++) {
sum += 1;
}
Pros:
Cons:
len
).Approach 2: for...in
Loop
let sum = 0;
for (let item in array) {
sum += item;
}
Pros:
Cons:
In this case, for...in
loop is not designed to iterate over array elements directly. It will iterate over the array object itself and include both numeric and non-numeric properties in the iteration. This can lead to unexpected behavior if the array contains objects with certain properties.
Approach 3: forEach()
Method
array.forEach(function(item, index) {
sum += item;
});
Pros:
Cons:
item
is an object with an index.In this case, the forEach()
method provides a convenient and readable way to iterate over the array. The callback function takes two arguments: the current element (item
) and its index (index
). This approach can be more efficient than traditional loops for large datasets, but it may incur additional overhead due to function calls.
Special Considerations
forEach()
method is implemented as a part of the ECMAScript standard, so its behavior and performance characteristics are well-defined.Alternatives
For large datasets or performance-critical code, alternative approaches such as:
map()
method to create a new array with transformed elements.reduce()
method to accumulate values in an accumulator.These alternatives can offer better performance and control over iteration, especially for large datasets or complex computations.
In conclusion, each approach has its strengths and weaknesses. When choosing an iteration method, consider factors such as dataset size, performance requirements, and code readability.