⚡️ Speed up function fibonacci by 16%
#1097
Open
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.
📄 16% (0.16x) speedup for
fibonacciincode_to_optimize_js/fibonacci.js⏱️ Runtime :
84.2 microseconds→72.9 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 15% speedup by replacing the recursive fast-doubling implementation with an iterative bit-scanning approach that eliminates two key sources of overhead:
What changed:
Eliminated recursion overhead: The original code recursively computes
fastDoubling(k/2), building up a call stack of depth O(log n). The optimized version uses a loop to process bits iteratively, avoiding all function call overhead.Removed array allocations: The original returns
[F(k), F(k+1)]arrays at each recursion level, creating O(log n) temporary arrays that require allocation and garbage collection. The optimized version maintains just two scalar variables (aandb) throughout execution.Direct bit manipulation: Instead of dividing and recursing, the optimized code finds the most significant bit position once, then processes each bit from MSB to LSB using bitwise operations
(k & (1 << i)), which is more efficient than repeated division operations.Why this is faster:
Impact on workloads:
The optimization particularly benefits:
The non-integer memoization path remains unchanged, so mixed workloads with both integer and non-integer inputs see benefits only on the integer cases.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-fibonacci-mkhhsh3wand push.