array = Array(10000).fill().map(_ => Math.random());
var length = array.length;
var sum = 0;
for (var i = 0; i < length; ++i) {
sum += array[i];
}
var sum = 0;
for (var i = 0; i < array.length; ++i) {
sum += array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
With separate length variable | |
Without separate length variable |
Test name | Executions per second |
---|---|
With separate length variable | 28705.8 Ops/sec |
Without separate length variable | 28750.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of two different approaches for looping over an array in JavaScript:
var length = array.length;
)array.length
property directly in the loop condition (for (var i = 0; i < array.length; ++i) { ... }
)Options Compared
The two options being compared are:
array.length
directly in the loop condition.Pros and Cons
Pros:
Cons:
Pros:
Cons:
array.length
is repeated on every iteration, which can lead to slower performance.array.length
.Other Considerations
In general, using a separate variable to store the length (Option 1) is recommended when:
On the other hand, not using a separate variable (Option 2) might be preferred in situations where:
Library/External Functionality
None of the provided benchmark cases uses any external libraries or functions. The script and array creation are performed directly within the benchmark code.
Special JS Feature/Syntax
No special JavaScript features or syntax are mentioned in this benchmark case. However, if you'd like to know about other relevant options or alternatives, I can provide some additional context.
Alternatives
If you're interested in exploring alternative approaches or optimizations for array looping, here are a few examples:
for...of
loop instead of traditional for...in
loopKeep in mind that these alternatives may require additional setup, configuration, and expertise.