Running#
After configuring the runtime environment according to the Foundry official documentation, execute the following commands under this project to see the actual gas difference comparison.
forge test --contracts 01_Constant/Constant.t.sol --gas-report
Function Description#
-
constant: Declares a constant, which needs to be assigned at the time of declaration and cannot be changed later.
-
immutable: Declares a constant, which can be assigned at the time of declaration and in the constructor, and cannot be changed later.
-
Variable: Declares a variable, which can be assigned at any stage and can be changed later.
DemoCode#
Below, three variables are defined using different modifiers.
contract Constant {
uint256 public constant varConstant = 1000;
uint public immutable varImmutable = 1000;
uint public variable = 1000;
}
The following is a gas difference comparison for reading variables in three scenarios. Gas optimization suggestions are as follows:
-
Based on the actual situation, try to avoid using
variable
to define variables. -
For constants that do not need to be modified, it is recommended to use
immutable
for definition, which is the best in terms of functionality and gas.
Keyword | Gas Consumption | Savings | Result |
---|---|---|---|
constant | 183 | 2122(≈92%)| ✅ Recommend | |
immutable | 161 | 2144(≈93%) | ✅ Recommend | |
variable | 2305 |