⚡️ Speed up function fibonacci by 138%
#1108
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.
📄 138% (1.38x) speedup for
fibonacciincode_to_optimize_ts/fibonacci.ts⏱️ Runtime :
3.96 microseconds→1.66 microsecondss(best of250runs)📝 Explanation and details
The optimized code achieves a 137% speedup by replacing the recursive algorithm with an iterative approach. Here's why this matters:
What changed:
prev,curr) to track consecutive Fibonacci numbers, achieving O(n) time complexity.Why it's faster:
fibonacci(n), the recursive version makes ~2^n function calls due to overlapping subproblems. For example,fibonacci(5)recalculatesfibonacci(3)twice andfibonacci(2)three times.n-1iterations with simple arithmetic operations, making it dramatically more efficient.Line profiler evidence:
Performance impact:
This optimization scales exponentially better with larger
nvalues. While the speedup is 137% for the tested inputs (reducing runtime from 3.96µs to 1.66µs), the gains become massive for larger Fibonacci numbers—potentially reducing seconds or minutes to milliseconds. The optimization is particularly beneficial if this function is called in hot paths or with varying input sizes.✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mklovcbpand push.