Skip to content

Commit edf70e5

Browse files
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

File tree

code_to_optimize_js/fibonacci.js

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,28 @@ function fibonacci(n) {
1212
if (n <= 1) {
1313
return n;
1414
}
15-
return fibonacci(n - 1) + fibonacci(n - 2);
15+
16+
// Fast path for non-negative integer inputs (O(n) time, O(1) memory)
17+
if (Number.isInteger(n) && n >= 0) {
18+
let a = 0;
19+
let b = 1;
20+
for (let i = 2; i <= n; i++) {
21+
const c = a + b;
22+
a = b;
23+
b = c;
24+
}
25+
return b;
26+
}
27+
28+
// Fallback to the original recursive behavior for other numeric inputs
29+
function slow(x) {
30+
if (x <= 1) {
31+
return x;
32+
}
33+
return slow(x - 1) + slow(x - 2);
34+
}
35+
36+
return slow(n);
1637
}
1738

1839
/**

0 commit comments

Comments
 (0)