⚡️ Speed up function fibonacci by 122%
#1105
Closed
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.
📄 122% (1.22x) speedup for
fibonacciincode_to_optimize_ts/fibonacci.ts⏱️ Runtime :
4.71 microseconds→2.12 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 121% speedup (2.2x faster) by replacing the exponentially complex recursive approach with an iterative solution that eliminates redundant calculations and function call overhead.
Key Optimization:
The original code uses naive recursion where
fibonacci(n)recursively calls itself twice for each level, leading to O(2^n) time complexity. This creates a massive tree of duplicate calculations—for example,fibonacci(5)would calculatefibonacci(3)multiple times.The optimized version uses iterative dynamic programming with two variables (
prevandcurr) to build up the Fibonacci sequence from bottom to top in a single pass. This achieves O(n) time complexity with O(1) space complexity.Why It's Faster:
Performance Characteristics:
nincreases (the 121% speedup shown is likely for a small n; for n=30+, the difference would be orders of magnitude)This is a textbook example of converting exponential recursion to linear iteration—one of the most impactful algorithmic optimizations available.
✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mklgpc1fand push.