Commit 40efa80
authored
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
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
16 | 26 | | |
17 | 27 | | |
18 | 28 | | |
| |||
0 commit comments