๐ŸŽ’Gas Saving Technique 23: Public to private constants

Introduction:

Within a smart contract, the visibility of constants can have a subtle but notable impact on gas usage. This tutorial will guide you through the benefits of adjusting the visibility of constants from public to private or internal as a means of saving gas.

Understanding the Impact:

In Solidity, public variables have an automatically generated getter function, which, although useful, incurs extra gas cost during contract deployment. If a constant doesn't need to be accessed outside of the contract or derived contracts, changing its visibility can result in gas savings.

Vulnerability Details:

Deploying a contract with numerous public constants can unnecessarily increase its deployment gas cost due to the added getter functions. Moreover, every time these constants are accessed, additional gas is used.

Example:

Using public constant:

solidityCopy codepragma solidity ^0.8.0;

contract GasSaver {
    // Public constant with generated getter function
    uint256 public constant SOME_VALUE = 12345;
}

Optimized Version Using internal constant:

solidityCopy codepragma solidity ^0.8.0;

contract GasSaver {
    // Internal constant without generated getter function
    uint256 internal constant SOME_VALUE = 12345;
}

Mitigation Steps:

  1. Review Constants: Examine your contract for public constants.

  2. Adjust Visibility: If a constant doesnโ€™t need to be accessed outside of the contract or by derived contracts, consider changing its visibility to internal. If it does not need to be accessed by derived contracts either, consider making it private.

  3. Test the Contract: Ensure your contract still behaves as expected after making visibility adjustments.

Benefits:

  • Gas Efficiency: Reducing visibility can save gas on contract deployment and when accessing constants.

  • Encapsulation: It promotes better encapsulation and contract abstraction, enhancing contract security and readability.

Consideration:

  • Accessibility: Ensure that no external component relies on the visibility of these constants before making changes.

Conclusion:

While the gas savings might be minor per operation, in contracts with high transaction volume or many constants, these savings accumulate. Additionally, this practice enhances the encapsulation within your contract, promoting a cleaner and more secure codebase. Always test thoroughly after making optimizations to ensure the contract's functionality remains intact.

Last updated