⚡️ Speed up method Algorithms.fibonacci by 12%
#1421
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.
📄 12% (0.12x) speedup for
Algorithms.fibonacciincode_to_optimize/java/src/main/java/com/example/Algorithms.java⏱️ Runtime :
4.37 milliseconds→3.88 milliseconds(best of5runs)📝 Explanation and details
This optimization achieves a 12% runtime improvement (from 4.37ms to 3.88ms) by streamlining the bit-scanning loop in the fast-doubling Fibonacci algorithm.
Key Change:
The original code computed
(n >>> i) & 1on every iteration, requiring two operations: a right-shift ofnbyibits, then a bitwise AND. The optimized version precomputes a bitmask (mask = 1 << highestBit) and shifts only the mask right each iteration (mask >>>= 1), checking bits via(n & mask) == 0.Why This is Faster:
nright by varying amounts each loop iteration, we shift a single-bit mask (always a power of 2) right by one position. Shifting a mask is cheaper than repeatedly shiftingn.nwithout needing to shiftnitself, reducing instruction complexity in the hot loop.>>>= 1), which modern CPUs can optimize more effectively than variable-distance shifts.Impact:
The fast-doubling algorithm processes each bit of
nexactly once (from MSB to LSB), so for Fibonacci numbers at positionn, the loop runs⌊log₂(n)⌋ + 1times. This optimization reduces the per-iteration overhead by eliminating the variable right-shift ofn, yielding measurable speedup especially for largernvalues where the loop iterates more times. The 12% improvement demonstrates that even small reductions in tight loop overhead compound significantly across iterations.✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
To edit these changes
git checkout codeflash/optimize-Algorithms.fibonacci-mlbhxpv8and push.