๐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:
Optimized Version Using internal
constant:
Mitigation Steps:
Review Constants: Examine your contract for
public
constants.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 itprivate
.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