โก๏ธGas Saving Technique 26: Shift Right instead of Dividing by 2
Introduction: When dealing with smart contracts, every gas unit counts. Optimizing operations, especially arithmetic ones, can lead to significant savings. A common operation seen in contracts is division by 2. While this operation is straightforward, it may not be the most gas-efficient. In this tutorial, we'll explore a more efficient method using the bitwise right shift operation.
Concept: In binary arithmetic, shifting a number one position to the right is equivalent to dividing it by 2. Similarly, shifting left equates to multiplying by 2. Solidity provides the >>
operator for the bitwise right shift. When replacing division by 2 with the right shift operation, we achieve two primary advantages:
Gas Efficiency: The EVM's
DIV
opcode consumes 5 gas. In contrast, theSHR
(Shift Right) opcode only requires 3 gas, leading to a 40% reduction in gas for this operation.Bypass Additional Checks: Solidity's division operation includes a check for division-by-zero. When using bitwise shifting, we bypass this check, thus saving additional gas.
Example:
In the given code snippet:
We can replace the division by 2 with a bitwise right shift for efficiency:
Recommendation:
Identify areas in your code where division by 2 is used.
Replace the division operation with a bitwise right shift.
Ensure the context and logic still make sense after the change, especially when handling negative values or when precision is paramount.
Conclusion:
Optimizing smart contracts for gas efficiency is crucial, especially when deploying and interacting with them on networks with high gas costs. Replacing divisions by 2 with bitwise right shifts is a simple yet effective way to save on gas. This change doesn't compromise the code's readability, making it a worthwhile optimization to consider in your contracts.
Last updated