const smallN = 2 ** 10
const bigN = 2 ** 20
const arr1 = []
const arr2 = []
for (let i = 0; i < bigN; ++i) {
arr1.push(Math.random())
arr2.push(Math.random())
}
for (let i = 0; i < bigN; ++i) {
arr1[i] *= 2
arr2[i] *= 2
}
for (let i = 0; i < bigN; ++i) arr1[i] *= 2
for (let i = 0; i < bigN; ++i) arr2[i] *= 2
for (let i = 0; i < smallN; ++i) {
arr1[i] *= 2
arr2[i] *= 2
}
for (let i = 0; i < smallN; ++i) arr1[i] *= 2
for (let i = 0; i < smallN; ++i) arr2[i] *= 2
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
single loop (big N) | |
separate loops (big N) | |
single loop (small N) | |
separate loops (small N) |
Test name | Executions per second |
---|---|
single loop (big N) | 322.2 Ops/sec |
separate loops (big N) | 280.3 Ops/sec |
single loop (small N) | 345163.3 Ops/sec |
separate loops (small N) | 260841.3 Ops/sec |
This benchmark tests different approaches to iterating over arrays in JavaScript. Specifically, it compares the performance of using a single loop versus multiple separate loops for both small (2^10) and large (2^20) arrays.
for (let i = 0; i < bigN; ++i) {
arr1[i] *= 2;
arr2[i] *= 2;
}
for (let i = 0; i < bigN; ++i) arr1[i] *= 2;
for (let i = 0; i < bigN; ++i) arr2[i] *= 2;
for (let i = 0; i < smallN; ++i) {
arr1[i] *= 2;
arr2[i] *= 2;
}
for (let i = 0; i < smallN; ++i) arr1[i] *= 2;
for (let i = 0; i < smallN; ++i) arr2[i] *= 2;
Single Loop:
Pros:
Cons:
Separate Loops:
Pros:
Cons:
Other alternatives to iterating over arrays in JavaScript include:
forEach
, map
, reduce
): These can improve readability and clarity but can incur additional overhead, especially for very large datasets.In conclusion, this benchmark provides a clear view of the performance differences when handling common JavaScript array operations and highlights the trade-offs between single and multi-loop constructs.