Non-zero Rule
Writing storage variables from 1
to 2
saves tremendous amount of gas, comparing to writing from 0
to 1
. Or to put this to a more general rule, writing from non-zero to non-zer is much better than writing from zero to one.
Example
pragma solidity ^0.8.17;
uint256 varZero = 0;
uint256 varOne = 1;
function zeroToOne() external{
varZero = 1; // This operation is gas-intensive
}
function oneToTwo() external{
varOne = 2; // This operation is far more gas-efficient
}
Calling function zeroToOne
would cost 20022 gas and calling function oneToTwo
sould cost 116 gas only, proving that altering from zero to one is about 172 times more gas-consuming than shifting from one to two.
Test Environment
- Compiler: solc 0.8.17
- Testing Framework: Foundry
ETH saved over 100 transactions
100 tx * 30 gwei * 0.000000001 * (20022-116) = 0.059718 ~= 0.06 ETH1
USD Saved over 100 transactions
- At \$4000 / ETH: \$240
- At \$3000/ETH: \$180
- At \$2000/ETH: \$120
-
Assumed gas price: 30 gwei ↩