kasoqian

kasoqian

区块链步道师,传播区块链技术

Gas Optimization Column: 01 constant, immutable, variables

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#

  1. constant: Declares a constant, which needs to be assigned at the time of declaration and cannot be changed later.

  2. immutable: Declares a constant, which can be assigned at the time of declaration and in the constructor, and cannot be changed later.

  3. 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:

  1. Based on the actual situation, try to avoid using variable to define variables.

  2. 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.

KeywordGas ConsumptionSavingsResult
constant1832122(≈92%)| ✅ Recommend
immutable1612144(≈93%) | ✅ Recommend
variable2305
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.