Skip to content

Commit 2ada65a

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

File tree

code_to_optimize_js_esm/fibonacci.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ export function fibonacci(n) {
1313
if (n <= 1) {
1414
return n;
1515
}
16+
17+
if (Number.isInteger(n)) {
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+
1628
return fibonacci(n - 1) + fibonacci(n - 2);
1729
}
1830

0 commit comments

Comments
 (0)