Skip to content

Commit 40efa80

Browse files
Optimize fibonacci
The optimized code achieves a **2853% speedup** (from 4ms to 135μs) by replacing the exponential-time recursive algorithm with a linear-time iterative approach. **What changed:** - **Eliminated recursion:** The original code uses naive recursion where `fibonacci(n)` calls itself twice (`fibonacci(n-1)` and `fibonacci(n-2)`), creating an exponential tree of duplicate calculations. - **Introduced iterative computation:** The optimized version uses a simple loop with two variables (`prev` and `curr`) to track consecutive Fibonacci numbers, building up to the result. **Why this is faster:** - **Time complexity:** Drops from O(2^n) to O(n). For `fibonacci(35)`, the original makes ~29 million recursive calls, while the optimized version performs just 33 loop iterations. - **No call stack overhead:** Eliminates the cost of creating and destroying function call frames, which is expensive in JavaScript. - **No redundant computation:** Each Fibonacci number is calculated exactly once instead of being recomputed thousands of times across different branches of the recursion tree. **Impact on workloads:** - **Large inputs:** The performance tests show this optimization is critical for inputs like `n=35`, where the original would take seconds (and risk stack overflow at `n=1000`), while the optimized version completes in microseconds. - **Moderate inputs (n=15-25):** Even for smaller values tested, the speedup is substantial and prevents timeouts in CI environments. - **Edge cases preserved:** The optimization maintains identical behavior for base cases (`n ≤ 1`) and supports the same type coercion patterns tested with null and numeric strings. **Test case performance:** The optimized version excels particularly in the "Performance tests" suite, making previously slow or stack-overflow-prone cases (`n=35`, `n=1000`) trivially fast and preventing the deep recursion failures that the original implementation suffered from.
1 parent 5463287 commit 40efa80

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

code_to_optimize_js/fibonacci.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,17 @@ function fibonacci(n) {
1212
if (n <= 1) {
1313
return n;
1414
}
15-
return fibonacci(n - 1) + fibonacci(n - 2);
15+
16+
let prev = 0;
17+
let curr = 1;
18+
19+
for (let i = 2; i <= n; i++) {
20+
const next = prev + curr;
21+
prev = curr;
22+
curr = next;
23+
}
24+
25+
return curr;
1626
}
1727

1828
/**

0 commit comments

Comments
 (0)