⚡️ Speed up function fibonacci by 50,481%
#1096
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.
📄 50,481% (504.81x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
36.2 milliseconds→71.7 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a ~505x speedup (from 36.2ms to 71.7μs) by replacing the exponential-time naive recursion with two algorithmic improvements:
Key Optimizations
1. Fast Doubling Algorithm for Integer Inputs (O(log n) complexity)
2. Memoization for Non-Integer Inputs (O(n) complexity)
Why This Works
The original naive implementation has O(2^n) time complexity because it recomputes the same Fibonacci values exponentially many times. For example, computing F(32) requires ~4,294,967,295 function calls.
The fast doubling algorithm leverages bit manipulation (
(k / 2) | 0for integer division,k & 1for parity checks) to divide-and-conquer in O(log n) depth, dramatically reducing total operations.Test Case Performance
The optimization is particularly valuable for any workload involving moderate-to-large Fibonacci computations, transforming an impractical algorithm into one suitable for production use.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhha7nmand push.