⚡️ Speed up function fibonacci by 51,311%
#1094
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.
📄 51,311% (513.11x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
7.21 milliseconds→14.0 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 515x speedup (from 7.21ms to 14μs) by replacing the recursive algorithm with an iterative approach that eliminates exponential redundant calculations.
What changed:
fibonacci(n-1)andfibonacci(n-2)at each level, creating an exponential call tree where the same values are recalculated thousands of times (e.g.,fibonacci(2)is computed over 10,000 times when calculatingfibonacci(20)).forloop with two variables (prevandcurr) to iteratively build up the Fibonacci sequence from bottom to top, computing each value exactly once.Why this is faster:
n=30, this means ~1 billion operations reduced to just 30 iterations.Test case performance:
The optimization particularly benefits larger inputs (n≥20), where the exponential growth of the recursive approach becomes prohibitive. The test suite shows correct results for n=20, 25, and 30, which would be slow or impractical with the recursive version. Smaller inputs (n≤10) also benefit but the speedup is less pronounced since the base cases dominate.
Impact:
This optimization makes the function viable for production use with moderate-to-large inputs, transforming it from an academic example into a practical implementation suitable for any context where Fibonacci numbers need to be computed efficiently.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhg51vfand push.