var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function sum_recurse(arr, i) {
i = i || 0;
if (i > arr.length)
return 0;
else
return arr[i] + sum_recurse(arr, i + 1);
}
function sum_recurse_tail(arr, i, sum = 0) {
i = i || 0;
if (i > arr.length)
return 0;
else
return sum_recurse(arr, i + 1, sum + arr[i]);
}
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)
sum_recurse_tail(nums)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
recursion | |
while loop | |
for loop | |
recurse (tail) |
Test name | Executions per second |
---|---|
recursion | 548839.1 Ops/sec |
while loop | 3232907.8 Ops/sec |
for loop | 3647159.5 Ops/sec |
recurse (tail) | 569380.4 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Definition
The benchmark compares four different approaches to sum up an array of numbers:
sum_recurse
that adds each element in the array recursively, with a twist. The function takes two arguments: arr
and i
, where i
is the current index. If i
exceeds the length of the array, the function returns 0. Otherwise, it calls itself with i + 1
and adds the current element to the sum.sum_recurse
that is similar to the previous one but without the optimization for tail recursion.Options Compared
The benchmark compares the execution time of these four approaches on the same input data:
nums
: an array of 10 numbers from 1 to 10Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and Special JS Feature
The benchmark uses JavaScript, which is a high-level, interpreted language with many built-in features. There are no external libraries mentioned in the benchmark definition. However, the benchmark does utilize:
Other Considerations
When writing benchmarks like this one, it's essential to consider factors such as:
Alternatives
If you're looking for alternative approaches, consider:
Keep in mind that the choice of approach depends on the specific problem and requirements.