Constant Rule
Use constant whenever you can. The value is embedded to the bytecode of the contract when you use constant, this saves gas because we don’t make any cold storage read.
Example
pragma solidity ^0.8.17;
contract Constants {
address constant constantRouter = 0xe592427a0aece92de3edee1f18e0157c05861564;
address public storageRouter = 0xe592427a0aece92de3edee1f18e0157c05861564;
function getConstant() external pure returns (address) {
return constantRouter;
}
function getStorage() external view returns (address) {
return storageRouter;
}
}
Calling function getStorage
would cost 136 gas and calling function getConstant
would cost 18 gas only, proving that using constant variables help saves almost seven times the gas cost.
Test Environment
- Compiler: solc 0.8.17
- Testing Framework: Foundry
ETH saved over 100 transactions
100 tx * 30 gwei * 0.000000001 * (136-18) = 0.000354 ~= 0.0004 ETH1
USD Saved over 100 transactions
- At \$4000 / ETH: \$1.6
- At \$3000/ETH: \$1.2
- At \$2000/ETH: \$0.8
-
Assumed gas price: 30 gwei ↩