⚡️ Speed up function fibonacci by 100%
#1110
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.
📄 100% (1.00x) speedup for
fibonacciincode_to_optimize_ts/fibonacci.ts⏱️ Runtime :
4.00 microseconds→2.00 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 100% speedup (2x faster) by eliminating the exponential time complexity of naive recursive Fibonacci calculation through two key optimizations:
1. Memoization to eliminate redundant calculations:
The original recursive implementation recalculates the same Fibonacci values exponentially many times. For example,
fibonacci(5)callsfibonacci(3)twice,fibonacci(2)three times, etc., leading to O(2^n) time complexity. The optimized version uses aMapto cache results, ensuring each Fibonacci number is computed only once.2. Fast iterative path for integer inputs:
For integer values of
n(the common case), the optimized code uses a bottom-up iterative approach instead of recursion. This is significantly faster because:The line profiler shows this efficiency: the original code had 1200 hits on the recursive call line, while the optimized version has dramatically fewer hits (19 total on the entry point) and executes primarily through the fast iterative loop (lines 32-35 with 35-36 hits).
Non-integer fallback: For non-integer inputs, the code preserves the original recursive behavior with memoization, maintaining correctness while still gaining performance benefits from caching.
Impact: This optimization is especially valuable for:
nvalues (memoization pays off immediately)nwhere the exponential blowup of naive recursion becomes severe✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mklqrgwjand push.