⚡️ Speed up function fibonacci by 124%
#1107
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.
📄 124% (1.24x) speedup for
fibonacciincode_to_optimize_ts/fibonacci.ts⏱️ Runtime :
3.91 microseconds→1.75 microsecondss(best of250runs)📝 Explanation and details
The optimized code achieves a 124% speedup by replacing the exponential-time recursive algorithm with a linear-time iterative approach.
Key Changes:
fibonacci(n-1) + fibonacci(n-2), causing exponential growth in function calls—forfibonacci(10), this creates hundreds of redundant calculations.prevandcurr) to track the last two Fibonacci numbers, computing each value exactly once in a forward loop.Why This Is Faster:
fibonacci(5)gets computed multiple times when calculatingfibonacci(10)). The iterative version calculates each Fibonacci number exactly once.n, while the iterative version uses only three variables regardless of input size.Performance Impact:
Even at small values like n=10 (based on the ~4μs runtime suggesting modest input), the speedup is noticeable. For larger values (n>30), the difference becomes dramatic—exponential vs. linear growth means the original would take seconds while the optimized version remains sub-millisecond.
Best For:
This optimization excels with any n > 10, where the exponential cost of recursion becomes prohibitive. The iterative approach maintains consistent, predictable performance scaling.
✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mklolrdoand push.