function getAverage(numbers) {
return numbers.reduce((a, b) => a + b, 0) / numbers.length || 0;
}
getAverage(1, 2, 3, 4, 5);
function getAverage(numbers) {
let sum = 0, i = len = numbers.length;
while (i--) sum += numbers[i];
return sum / len || 0;
}
getAverage(1, 2, 3, 4, 5);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce | |
For loop |
Test name | Executions per second |
---|---|
Reduce | 229547584.0 Ops/sec |
For loop | 6415757.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark in question compares two approaches to calculate the average of an array of numbers: using the reduce()
method versus a traditional for loop. The test cases are identical, with the same input data ([1, 2, 3, 4, 5]
) and no external dependencies.
Options Compared
The benchmark tests two options:
reduce()
method to calculate the sum of the numbers in the array and then divides by the length of the array.Pros and Cons
Reduce Method:
Pros:
reduce()
Cons:
For Loop:
Pros:
reduce()
)Cons:
reduce()
methodLibrary Usage
None of the test cases use external libraries, which is good since we want a fair comparison between the two approaches.
Special JavaScript Features or Syntax
There are no special features or syntax used in this benchmark. The code is standard JavaScript, with no experimental or non-standard features like async/await or decorators.
Other Alternatives
If you're interested in exploring alternative approaches to calculating averages, here are a few:
sum
function: This utility function can be used instead of the reduce()
method. It's a convenient option when working with Lodash and doesn't require manual handling of arrays.reduce()
for large arrays.In summary, the benchmark provides a straightforward comparison between two approaches to calculating averages: the concise and efficient reduce()
method versus a traditional for loop. While there are some pros and cons associated with each approach, the choice ultimately depends on your specific use case and performance requirements.