⚡️ Speed up function fibonacci by 129,878%
#1090
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.
📄 129,878% (1,298.78x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
8.55 milliseconds→6.58 microseconds(best of250runs)📝 Explanation and details
The optimized code applies memoization to eliminate redundant recursive calls, dramatically reducing time complexity from exponential O(φ^n) ≈ O(1.618^n) to linear O(n).
Key Changes:
Map-based cache to store previously computed Fibonacci valuesWhy This Is Faster:
The naive recursive implementation recomputes the same Fibonacci values exponentially many times. For example,
fibonacci(30)triggers over 2.6 million recursive calls. With memoization, each value from 0 to n is computed exactly once, reducing 30 calls to just 31 cache operations—a fundamental algorithmic improvement that scales exponentially better.Performance Impact:
fibonacci(30), the test completes well under the 2000ms threshold (vs. potentially minutes without caching)Test Case Analysis:
fibonacci(n-1) + fibonacci(n-2)) benefit from overlapping subproblems being cachedThe cache persists across function calls, making this optimization especially valuable in workloads with repeated or sequential Fibonacci queries.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhbpu8mand push.