function steps(n) {
for (let row = 0; row < n; row++) {
let stair = "";
for (let column = 0; column < n; column++) {
if (column <= row) {
stair += "#";
} else {
stair += " ";
}
}
console.log(stair);
}
}
steps(4)
function steps2(n, row = 0, stair = "") {
if (n === row) {
return;
}
if (n === stair.length) {
console.log(stair);
steps2(n, row + 1);
return;
}
if (stair.length <= row) {
stair += "#";
} else {
stair += " ";
}
steps2(n, row, stair);
}
steps2(4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Nested Loops | |
Recursion |
Test name | Executions per second |
---|---|
Nested Loops | 451004.2 Ops/sec |
Recursion | 182327.3 Ops/sec |
The benchmark "Recursion vs Nested Loops" is designed to compare two different programming approaches for generating a visual representation of steps that form one side of a Christmas tree using JavaScript: nested loops and recursion. The key characteristics of both approaches provide insights into performance and coding style.
Nested Loops
for
loops to achieve the desired output. The outer loop iterates over each row, and the inner loop constructs each line (or stair) by appending either a #
(for steps) or a space (for empty space).Recursion
In the tests executed on Chrome 130:
From these results, we can infer that the nested loops approach performed better than the recursive implementation in terms of execution speed. This is typical in JavaScript and many languages since iteration is generally more efficient than recursive calls due to the overhead associated with managing function call stacks.
When choosing between these two methods, engineers should consider factors such as:
Other alternatives to consider for such tasks include:
.map()
, .reduce()
, or recursion with functional styles (though this might involve creating additional function scopes).