โน๏ธ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 a SLOAD operation after it's set.

Example:

Original Code with Storage Variables:

solidityCopy codepragma solidity ^0.8.0;

contract GasSaver {
    uint private _concurShareMultiplier = 1e18;
    uint private _perMille = 1000; // 100%
}

Optimized Code with Constant Variables:

solidityCopy codepragma solidity ^0.8.0;

contract GasSaver {
    uint private constant CONCUR_SHARE_MULTIPLIER = 1e18;
    uint private constant PER_MILLE = 1000; // 100%
}

Or if the values are to be assigned during construction:

solidityCopy codepragma solidity ^0.8.0;

contract GasSaver {
    uint private immutable CONCUR_SHARE_MULTIPLIER;
    uint private immutable PER_MILLE; // 100%

    constructor() {
        CONCUR_SHARE_MULTIPLIER = 1e18;
        PER_MILLE = 1000;
    }
}

Mitigation Steps:

  1. Identify Variables: Look for variables in your contract that are set once and never change.

  2. Convert to Constants or Immutable: If a variable is known at compile time, make it a constant. If itโ€™s determined at construction, make it immutable.

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