⚡️ Speed up function fibonacci by 7,083%
#1092
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.
📄 7,083% (70.83x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
1.96 milliseconds→27.3 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 71x speedup (7082%) by eliminating the exponential time complexity of the original naive recursive Fibonacci implementation.
What changed:
O(n)loop with two variables (a,b) replaces the recursive tree, avoiding exponential branching entirely.Mapcache stores previously computed results, preventing redundant recursive calls while preserving the original semantics for edge cases likefibonacci(1.5).Why this is faster:
The original recursive implementation has
O(2^n)time complexity because each call spawns two more calls, leading to massive redundant computation. Forfibonacci(25), this results in millions of duplicate calls. The iterative approach computes each Fibonacci number exactly once in a tight loop, reducing complexity toO(n)withO(1)memory. For the common case of integer inputs (which all tests use), this is drastically faster.Test case performance:
fibonacci(25)shows this is where the optimization shines—original complexity explodes here.Impact on workloads:
Since no
function_referencesare provided, we can't determine if this is in a hot path. However, any caller repeatedly computing Fibonacci numbers (e.g., in a loop or batch processing) will see compounding benefits. The optimization is most effective forn > 15, where the naive approach becomes prohibitively slow.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhclwqdand push.