Commit edf70e5
authored
Optimize fibonacci
The optimized code achieves a **1140x speedup** (from 33.8ms to 29.6μs) by replacing the exponential-time recursive algorithm with a linear-time iterative approach for the most common case: non-negative integers.
**Key Changes:**
1. **Fast Path for Integers (O(n) vs O(2^n))**: The optimization adds a check for `Number.isInteger(n) && n >= 0` and computes Fibonacci iteratively using just two variables (`a` and `b`). This eliminates the exponential explosion of recursive calls that occurs with the naive implementation—for example, `fibonacci(20)` requires ~21,891 recursive calls in the original but only 19 iterations in the optimized version.
2. **Preserves Original Semantics**: For edge cases like negative numbers, floats, or string coercions, the code falls back to the original recursive implementation (`slow()`), ensuring behavioral compatibility.
**Why This Works:**
- **Eliminates Redundant Computation**: The naive recursion recomputes the same Fibonacci values exponentially many times (e.g., `fibonacci(2)` is called thousands of times when computing `fibonacci(20)`). The iterative approach computes each value exactly once.
- **Minimal Memory Overhead**: Uses O(1) space instead of O(n) call stack depth, preventing stack overflow on larger inputs.
**Test Results Show:**
- **Large inputs benefit massively**: Performance tests computing `fibonacci(0)` through `fibonacci(30)` now complete in microseconds instead of seconds. The test expecting completion under 3000ms would pass trivially with the optimized version.
- **Small inputs remain fast**: Basic cases (0-10) already execute quickly but still benefit from eliminating function call overhead.
- **Edge cases preserved**: Tests with negative numbers, floats (e.g., `fibonacci(1.5)`), and string coercion (`fibonacci('6')`) still pass because the fallback path maintains exact original behavior.
**Impact:**
For typical workloads using integer inputs (which represent 100% of canonical Fibonacci use cases), this optimization delivers transformative performance gains while maintaining full backward compatibility for unusual inputs.1 parent 7215c2b commit edf70e5
1 file changed
Lines changed: 22 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 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
16 | 37 | | |
17 | 38 | | |
18 | 39 | | |
| |||
0 commit comments