โ๏ธGas Saving Technique 2: Immutable Variable
Introduction
Gas optimization is essential in the development of smart contracts on the Ethereum network. One effective technique to achieve this involves using immutable
variables. An immutable
variable can save a significant amount of gas as it is assigned once at the time of contract deployment and is read-only thereafter. It offers an advantage over constant
variables, which are evaluated every time they are accessed, consuming more gas in the process.
Understanding immutable
Variable Optimization
immutable
Variable OptimizationWhy Use immutable
?
Gas Efficiency: Unlike
constant
variables,immutable
variables are only computed and set during contract deployment. The assigned value is stored immutably, leading to gas savings during transactions as the value isn't recalculated each time it's accessed.Readability Preserved: Using
immutable
retains code readability while saving gas, providing clarity and efficiency in your smart contracts.
Practical Examples
Changing Storage Variables to immutable
Consider a contract where certain variables like bribeVault
wonโt change post-deployment. Using immutable
instead of a regular storage variable can lead to gas savings.
Hereโs a demonstration:
Making Unchanged Variables immutable
or constant
For variables that never change, like _concurShareMultiplier
and _perMille
, you should declare them as constant
or immutable
to save gas. Hereโs an example:
In situations where the variable value is computed dynamically during contract deployment but remains constant thereafter, immutable
is ideal:
Consequences and Considerations
Each usage of a "constant" may cost extra gas on each access. Although this cost is lower than storing the result in storage, itโs still more than using
immutable
.Since
constant
variables arenโt real constants in the compiled bytecode, they cannot be referenced in certain constant environments like assembly or other libraries.
Conclusion
Utilizing immutable
variables provides a clear path towards optimizing gas usage in your smart contracts without sacrificing code readability. Carefully identify and assign values that remain unchanged post-deployment as immutable
or constant
to leverage these benefits. Always conduct thorough testing to ensure the assigned values truly remain constant for the life of the contract.
Recommendation
[G-16] Gas: โconstantsโ expressions are expressions, not constants. Use โimmutableโ instead
Last updated