18 - Mutability & Gas
Compared to regular State Variables, the gas costs of constant and immutable variables are much lower:
-
For a constant variable, the expression assigned to it is copied to all the places where it is accessed and also re-evaluated each time. This allows for local optimizations.
-
Immutable variables are evaluated once at construction time and their value is copied to all the places in the code where they are accessed. For these values, 32 bytes are reserved, even if they would fit in fewer bytes. Due to this, constant values can sometimes be cheaper than immutable values.
- State Mutability
- Gas Costs
- constant: Copied @ Usage
- Local Optimizations
- immutable: Evaluated Once & Copied
- constant vs. immutable
- Storage/Gas Efficient