Zokyo Gas Savings
  • ⛽Zokyo Gas Savings
  • 📚Tutorials
    • ✔️Gas Saving Technique 1: Unchecked Arithmetic
    • ⛓️Gas Saving Technique 2: Immutable Variable
    • ✨Gas Saving Technique 3: Double star ** inefficiency
    • 💰Gas Saving Technique 4: Cache Array Length
    • ⬅️Gas Saving Technique 5: ++i costs less gas compared to i++
    • ⚖️Gas Saving Technique 6: NOT operator ! cheaper than boolean FALSE
    • 🪡Gas Saving Technique 7: Using Short Reason Strings
    • 🪵Gas Saving Technique 8: Use Custom Errors instead of Revert Strings to save Gas
    • ✒️Gas Saving Technique 9: Use Custom Errors instead of Revert Strings to save Gas
    • 👾Gas Saving Technique 10: Calldata cheaper than memory
    • ⛔Gas Saving Technique 11: > 0 is less efficient than != 0 for unsigned integers
    • ➗Gas Saving Technique 12: SafeMath no longer needed
    • 😮Gas Saving Technique 13: variables default to 0
    • 🧱Gas Saving Technique 14: struct layout/ variable packing
    • 📞Gas Saving Technique 15: Cache External Call
    • ✍️Gas Saving Technique 16: Early Validation before external call
    • 😎Gas Saving Technique 17: Don’t cache value that is used once
    • 😧Gas Saving Technique 18: Redundant code
    • ✅Gas Saving Technique 19: Early Validation before external call
    • ⛏️Gas Saving Technique 20: Storage vs Memory read optimizations
    • ✒️Gas Saving Technique 21: Unneeded If statements
    • 🌗Gas Saving Technique 22: >= is cheaper than >
    • 🎒Gas Saving Technique 23: Public to private constants
    • ⏹️Gas Saving Technique 24: Make unchanged variables constant/immutable
    • ⏱️Gas Saving Techniques 25: Redundant Access Control Checks
    • ➡️Gas Saving Technique 26: Shift Right instead of Dividing by 2
    • 🪃Gas Saving Tutorial 27: Efficient Boolean Comparison
    • 🤝Gas Saving Technique 28: && operator uses more gas
    • 👓Gas Saving Technique 29: x = x + y is cheaper than x += y
    • 👂Gas Saving Technique 30: Using 1 and 2 rather than 0 and 1 saves gas
    • ⚽Gas Saving Technique 31: Optimize Storage by Avoiding Booleans
    • 🔙Gas Saving Technique 32: Optimal Use of Named Return Variables in Solidity
    • 🛢️Gas Saving Technique 33: Making Functions Payable for Optimized Gas Costs
    • ✍️Gas Saving Technique 34: Optimizing Storage References in Smart Contracts
    • ⛰️Gas Saving Technique 35: Usage of uints/ints smaller than 32 bytes (256 bits) incurs overhead
    • 🌪️Gas Saving Technique 36: Inlining Single Use Internal Functions for Savings
    • ☄️Gas Saving Technique 37: Switching from Public to External Functions for Savings
    • 🎆Gas Saving Technique 38: Upgrading Solidity Compiler to Improve Gas Efficiency and Security
    • 🕶️Gas Saving Technique 39: Avoiding Duplicated Code for Gas Savings
    • 😄Gas Saving Technique 40: Removal of Unused Internal Functions for Gas Savings
    • 🖋️Gas Saving Tutorial 41: In-lining Single Use Modifiers For Gas Saving
    • ⛏️Gas Saving Technique 42: `require` vs`assert`
Powered by GitBook
On this page
  1. Tutorials

Gas Saving Technique 2: Immutable Variable

PreviousGas Saving Technique 1: Unchecked ArithmeticNextGas Saving Technique 3: Double star ** inefficiency

Last updated 1 year ago

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

Why 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:

solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ImmutableExample {
    // Before optimization
    // address public bribeVault;
    
    // After optimization
    address public immutable bribeVault;

    constructor(address _bribeVault) {
        // Immutable variables are assigned once at deployment
        bribeVault = _bribeVault;
    }
}

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:

solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ConstantsExample {
    // Before optimization
    // uint private _concurShareMultiplier = 1e18;
    // uint private _perMille = 1000;

    // After optimization
    uint private constant _concurShareMultiplier = 1e18;
    uint private constant _perMille = 1000;
}

In situations where the variable value is computed dynamically during contract deployment but remains constant thereafter, immutable is ideal:

solidityCopy code// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ImmutableDeploymentExample {
    // Using immutable for dynamically set constant values
    uint public immutable deploymentValue;

    constructor(uint _multiplier) {
        deploymentValue = _multiplier * 2; // This value is computed once at deployment
    }
}

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

📚
⛓️
Book an audit with Zokyo
[G-16] Gas: “constants” expressions are expressions, not constants. Use “immutable” instead