โน๏ธGas Saving Technique 24: Make unchanged variables constant/immutable
Introduction:
Smart contracts often use variables that donโt change after being set initially. For these variables, Solidity provides constant
and immutable
types, which allow for gas-efficient reading. This tutorial guides you through the process of optimizing gas usage by converting unnecessary storage variables to constants or immutable variables.
Understanding the Impact:
Constants: They are similar to
immutable
, but their value must be set at compile time. Constants don't occupy storage slots; their values are inserted directly into the bytecode.Immutable: These variables can only be assigned during contract construction and are constant afterward. Reading an
immutable
is cheaper gas-wise as it doesnโt require aSLOAD
operation after it's set.
Example:
Original Code with Storage Variables:
Optimized Code with Constant Variables:
Or if the values are to be assigned during construction:
Mitigation Steps:
Identify Variables: Look for variables in your contract that are set once and never change.
Convert to Constants or Immutable: If a variable is known at compile time, make it a
constant
. If itโs determined at construction, make itimmutable
.Test the Changes: After modifying the contract, ensure it still functions as expected.
Benefits:
Gas Savings: Reduces gas cost by avoiding
SLOAD
operations when accessing these variables.Readability: Enhances code readability and understanding, signaling to readers which variables should never change.
Conclusion:
Converting variables that don't change to constants or immutables is a straightforward optimization with substantial benefits, primarily when these variables are accessed frequently. This approach offers gas savings, improves contract readability, and helps enforce that some values remain constant throughout the contract's life. Ensure to thoroughly test any changes made to your contractโs code to maintain its integrity and functionality.
Last updated