From fb82cfdf71a2839d3a1d463784e32dc5a87b5d8f Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 23 Jan 2026 16:11:01 +0000 Subject: [PATCH] Optimize fibonacci MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimized code replaces the exponential-time recursive algorithm with a linear-time iterative approach, achieving a **111% speedup** (from 45.5μs to 21.5μs). **Key optimization:** - **Original:** Naive recursion with O(2^n) time complexity. Each call spawns two more recursive calls, creating an exponential tree of redundant calculations. For example, `fibonacci(5)` recalculates `fibonacci(3)` twice and `fibonacci(2)` three times. - **Optimized:** Iterative bottom-up computation with O(n) time complexity and O(1) space. Uses two variables (`prev`, `curr`) to track consecutive Fibonacci numbers, computing each value exactly once in a simple loop. **Why this is faster:** The recursive approach makes approximately 2^n function calls for input n, each with call stack overhead. The iterative version performs exactly n-1 loop iterations with minimal overhead—no function calls, no stack frames, just basic arithmetic operations. This eliminates both the exponential branching factor and the per-call overhead. **Test performance characteristics:** - Small inputs (n ≤ 10): Both implementations are fast, but the 2x speedup is already visible - Moderate inputs (n = 15-25): The optimization becomes critical—naive recursion slows dramatically while the iterative version remains nearly instant - The annotated tests confirm correctness is preserved across all cases, including edge cases (negative numbers, n ≤ 1) and sequential values **Impact:** This optimization is particularly valuable if `fibonacci()` is called with values above n=20 or invoked frequently in loops/hot paths, where the exponential cost of recursion would compound significantly. --- code_to_optimize_js_esm/fibonacci.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/code_to_optimize_js_esm/fibonacci.js b/code_to_optimize_js_esm/fibonacci.js index 0ee526315..1a299d4b4 100644 --- a/code_to_optimize_js_esm/fibonacci.js +++ b/code_to_optimize_js_esm/fibonacci.js @@ -13,7 +13,17 @@ export function fibonacci(n) { if (n <= 1) { return n; } - return fibonacci(n - 1) + fibonacci(n - 2); + + let prev = 0; + let curr = 1; + + for (let i = 2; i <= n; i++) { + const next = prev + curr; + prev = curr; + curr = next; + } + + return curr; } /**