Use Constants Instead of Variables When Possible
Last Updated on 24. March 2025 by Mario Oettler
Using constants for values that do not change also saves gas. Constant values are written into the bytecode of the contract. Hence reading from it saves expensive storage reads.
pragma solidity 0.8.29;
contract Const{
uint256 constant c1 = 1;
function getValue() public returns (uint256){
return c1;
}
}
This code uses variables.
pragma solidity 0.8.29;
contract Var{
uint256 c1 = 1;
function getValue() public returns (uint256){
return c1;
}
}
The following table shows the gas costs for deployment including setting the values and reading from the constant or variable respectively.
Deployment incl. setting variables | Reading variables | |
Constant | 104978 | 24581 |
Var | 130459 | 26996 |
As you can see, both writing and reading from a constant is cheaper than using a variable.