Division by two should use bit shifting
Learn about Solidity's division operator and how bit shifting can be a more efficient alternative. Discover how using the >> 1 operation instead of division can optimize gas usage and improve your smart contract's performance. See how the unchecked {} keyword can further enhance your code by eliminating unnecessary checks during division.
Category
gas
Languages
solidity
Analysis Layer
static
Severity
info
When performing division by two in Solidity, it is recommended to use bit shifting instead of the division operator ("/").
<x> / 2 is the same as <x> >> 1. The two operations achieve the same result but differ in gas cost and efficiency.
The division operator (/) incurs an overhead of 20 gas due to JUMPs to and from a compiler utility function that introduces checks. These checks can be avoided by using unchecked {} around the division by two.
Consider the following example:
pragma solidity ^0.8.0;
contract DivisionExample {
function divideByTwo(uint256 x) external view returns (uint256) {
return x / 2;
}
function shiftByOne(uint256 x) external view returns (uint256) {
return x >> 1;
}
}
In the divideByTwo function, division by two is achieved using the division operator (/). On the other hand, in the shiftByOne function, bit shifting (>> 1) is used.
To optimize the gas cost of the division operation, we can use bit shifting instead:
pragma solidity ^0.8.0;
contract DivisionExample {
function divideByTwo(uint256 x) external view returns (uint256) {
unchecked {
return (x / 2);
}
}
function shiftByOne(uint256 x) external pure returns (uint256) {
return x >> 1;
}
}
By using unchecked {} around the division operation, we inform the compiler to skip the checks and calculations performed when using the division operator ("/"). This results in lower gas cost and improved efficiency.
In conclusion, when performing division by two in Solidity, it is recommended to use bit shifting (>> 1) instead of the division operator ("/") to optimize gas cost and improve efficiency.