⚡️ Speed up function fibonacci by 1,408%
#1098
Open
+22
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 1,408% (14.08x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
220 microseconds→14.6 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 1408% speedup (220μs → 14.6μs) by replacing the exponential-time recursive algorithm with two specialized paths:
Key Optimizations
1. Iterative Fast Path for Integers (O(n) vs O(2^n))
The original naive recursion has exponential time complexity because it recomputes the same Fibonacci values repeatedly. For example,
fibonacci(5)callsfibonacci(3)twice,fibonacci(2)three times, etc.The optimized version detects non-negative integers (the common case) and uses an iterative loop that computes each Fibonacci number exactly once, storing only the last two values. This transforms O(2^n) time complexity into O(n) with O(1) memory.
2. Memoized Recursion Fallback
For non-integer inputs or edge cases, the code uses a shared cache (
fibonacci._cache) to store previously computed results. This ensures that even if recursion is needed, each unique input is calculated only once, preventing exponential blowup.Why This Works in JavaScript
Number.isInteger(n) && n >= 2) efficiently routes the common case to the fast pathfibonacci._cache) persists across calls without polluting global scopeTest Case Performance
The optimization particularly benefits:
The base cases (n ≤ 1) maintain identical behavior, and the memoization fallback preserves correctness for any unusual inputs while still providing significant speedup over pure recursion.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhj6jwwand push.