let limit = 100_000_000;
let a = 0;
for (let i = 0; i < limit; i++) {
a += i;
}
let a = 0;
for (let i = 0; i < limit; ++i) {
a += i;
}
let a = 0;
for (let i = 0; i < limit; i += 1) {
a += i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
i++ | |
++i | |
i += 1 |
Test name | Executions per second |
---|---|
i++ | 25.2 Ops/sec |
++i | 25.3 Ops/sec |
i += 1 | 25.6 Ops/sec |
The benchmark defined in the provided JSON focuses on testing the performance of three different ways to increment a variable in a loop in JavaScript. Specifically, it compares the following increment methods:
Each of these methods involves iterating through a loop from 0 to a specified limit (100,000,000
), with the variable i
being incremented in one of the three different ways during each iteration. The core operation in all test cases is the addition of the current value of i
to a variable a
, which collects the sum of all i
values from 0 to limit - 1
.
The benchmark results indicate the number of executions per second for each method when run in a specific environment (Chrome 130 on Windows). The recorded execution speeds are as follows:
The method i += 1 performed slightly better than both the postfix and prefix increment methods, though the performance differences are minimal.
i++ (Postfix Increment)
++i (Prefix Increment)
i += 1 (Addition Assignment)
i++
or ++i
may be more intuitive for those accustomed to C-style languages, while i += 1
explicitly conveys the operation being performed.while
loop: Instead of a for
loop, which implicitly handles iteration.Array.prototype.forEach()
or Array.from().forEach()
.In summary, the benchmark highlights the minute performance differences between incrementing techniques in JavaScript. For typical applications, the choice between these methods should largely depend on personal or team style preferences, given that the performance differences are minimal in general use cases. Always consider the context in which the code will run, as well as the readability and maintainability of the code.