window.arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99];
arr.reduce((a, b) => a + b, 0)
let sum = 0
for(let i = 0; i < arr.length; i++)
sum += arr[i]
let sum =0;
for (let i = arr.length; i--;)
sum += arr[i]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce | |
Incrementing For Loop | |
Decrementing For Loop |
Test name | Executions per second |
---|---|
Reduce | 547437.8 Ops/sec |
Incrementing For Loop | 23550.0 Ops/sec |
Decrementing For Loop | 44917.4 Ops/sec |
Measuring the performance of JavaScript code can be a complex task, and BenchmarkThat.net provides a helpful platform for comparing different approaches.
Overview of the Benchmark
The benchmark measures the performance of three different ways to calculate the sum of an array: using reduce()
, incrementing for loop
, and decrementing for loop
. The test case uses a predefined array with 50 elements, which is passed to each method.
Options Compared
arr.reduce((a, b) => a + b, 0)
: This option uses the built-in reduce()
method of JavaScript arrays. It iterates through the array, adding each element to a running total.Pros and Cons
arr.reduce()
:Library and Special JavaScript Features
None of these options rely on specific libraries or advanced JavaScript features. However, it's worth noting that some browsers may have optimizations for certain methods or loops, which could affect performance.
Other Considerations
When measuring performance in JavaScript, there are several other factors to consider:
reduce()
method creates a new array with the accumulated results, while traditional loops modify the original array.while
loops instead of for
loops.Alternatives
Other alternatives to these three options include:
forEach()
and adding a callback function: This approach uses the forEach()
method to iterate through the array and adds a callback function to calculate the sum.map()
and reduce()
in combination: This approach uses the map()
method to create an array of calculated values and then applies the reduce()
method to accumulate the results.Keep in mind that each alternative has its own pros and cons, and the best approach depends on the specific requirements of your project.