`++i` is more gas efficient than `i++` or `i += i` (if x = 1)
0xPr0f opened this issue · comments
++i
is more gas efficient than i++
or i += x
(if x = 1)
Severity
Which severity would you assign to this Issue?
- Gas Optimization
- Non-Critical
- Low Risk
- Med Risk
- High Risk
Description
writing a value to a slot that doesn’t have one will be more expensive than writing to one that does.
when incrementing an integer, ++i (return old value, then add 1) is cheaper than i++ (add 1, then return new value)
Example
🤦 Bad:
/// @dev Consumes ~21586 gas on average.
function war() external pure returns (uint256 result) {
uint i = 1;
result += i;
}
or
/// @dev Consumes ~21557 gas on average.
function bar() external pure returns (uint256 result) {
result ++;
}
🚀 Good:
/// @dev Consumes ~21530 gas on average.
function foo() external pure returns (uint256 result) {
++ result;
}
Background Information
https://m1guelpf.blog/d0gBiaUn48Odg8G2rhs3xLIjaL8MfrWReFkjg8TmDoM
Tagging @pmerkleplant for visibility
Many thanks! ❤️