⚡️ Speed up function fibonacci by 136%
#1106
Open
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.
📄 136% (1.36x) speedup for
fibonacciincode_to_optimize_ts/fibonacci.ts⏱️ Runtime :
3.83 microseconds→1.62 microsecondss(best of250runs)📝 Explanation and details
The optimized code achieves a 136% speedup by replacing the exponentially-complex recursive algorithm with an iterative approach that uses constant space and linear time.
Key Changes:
fibonacci(n-1) + fibonacci(n-2)), creating an exponential call tree with O(2^n) time complexity and massive redundant calculations.prevandcurr) to track the last two values needed for the next computation.Why This is Faster:
fibonacci(n-2)is calculated multiple times (e.g., when computingfibonacci(n-1), it recalculatesfibonacci(n-2)again). The iterative approach computes each value once.Performance Impact:
The 136% speedup at the measured input size is just the beginning—the improvement scales dramatically with larger inputs. For n=30, the speedup would be in the thousands; for n=40, it would be millions of times faster. Even for small inputs (n≤10), the elimination of function call overhead provides measurable gains.
This optimization is universally beneficial regardless of where
fibonacci()is called, but especially valuable if invoked in loops or with moderate-to-large input values.✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mklo5q5kand push.