var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function sum_recurse(arr, i=0, acc=0) {
if (i > arr.length)
return acc;
acc += i[i];
return sum_recurse(arr, i + 1, acc);
}
function sum_while(arr) {
var total = 0,
i = 0,
len = arr.length;
while (i < len) {
total += arr[i++];
}
return total;
}
function sum_for(arr) {
var total = 0,
len = arr.length;
for (var i = 0; i < len; i++) {
total += arr[i];
}
return total;
}
sum_recurse(nums)
sum_while(nums)
sum_for(nums)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
recursion | |
while loop | |
for loop |
Test name | Executions per second |
---|---|
recursion | 770381.5 Ops/sec |
while loop | 8892113.0 Ops/sec |
for loop | 8894490.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between three different approaches for summing up an array of numbers: Recursion, While Loop, and For Loop.
Options Compared
The three options being compared are:
sum_recurse
function calls itself until it reaches the end of the array.sum_while
function uses a while loop to iterate through the array and sum up its elements.sum_for
function uses a for loop to iterate through the array and sum up its elements.Pros and Cons
Here are some pros and cons of each approach:
Library Used
There is no explicit library used in this benchmark. The sum_recurse
, sum_while
, and sum_for
functions are simple implementations of each approach, and the nums
array is a standard JavaScript array.
Special JS Feature/Syntax
None of the test cases use any special JavaScript features or syntax beyond the basics (e.g., array operations, loops). However, it's worth noting that some browsers may have specific optimizations or extensions that could affect the results of this benchmark.
Alternative Approaches
Some alternative approaches for summing up an array of numbers include:
Array.prototype.reduce()
: This is a more modern and efficient way to sum up an array using the reduce() method.Array.prototype.forEach()
: While not as efficient as reduce(), forEach can still be used to iterate over an array and perform some operation on each element.Overall, this benchmark provides a good starting point for understanding the performance differences between recursion, while loops, and for loops in JavaScript.