Commit 2ada65a
authored
Optimize fibonacci
The optimized code achieves a **94% speedup** (from 47.2μs to 24.3μs) by replacing exponential-time recursion with linear-time iteration for integer inputs.
**Key optimization:**
- **Algorithm change for integers**: Added an `Number.isInteger(n)` check that routes integer inputs to an iterative loop instead of recursive calls
- **Time complexity improvement**: For integer `n`, the original recursive approach has O(2^n) time complexity due to redundant recalculations, while the iterative approach runs in O(n) time with O(1) space
**Why this is faster:**
The original recursive fibonacci makes exponential function calls - for `fibonacci(10)`, it computes `fibonacci(5)` multiple times. The iterative approach calculates each fibonacci number exactly once by maintaining only two variables (`a` and `b`) and updating them in a forward loop.
For example, `fibonacci(20)`:
- **Original**: ~21,891 recursive calls
- **Optimized**: 19 loop iterations (plus one recursion check)
**Impact:**
- Integer inputs (the common case for fibonacci) see dramatic speedups that scale exponentially with input size
- Non-integer inputs fall through to the original recursive implementation, preserving backward compatibility
- The 94% speedup measured suggests the benchmark primarily tests integer inputs in a moderate range (likely n=10-30)
This is a classic dynamic programming optimization that eliminates redundant computation through a bottom-up iterative approach.1 parent c214e4e commit 2ada65a
1 file changed
Lines changed: 12 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
16 | 28 | | |
17 | 29 | | |
18 | 30 | | |
| |||
0 commit comments