โจGas Saving Technique 3: Double star ** inefficiency
Introduction
In Ethereum smart contracts, every gas unit saved matters. Even minor optimizations cumulatively lead to significant gas savings. One such subtle yet impactful optimization involves efficiently representing constant values, primarily focusing on avoiding the double star **
exponentiation operation where feasible and using alternative representations that are more gas-efficient.
Double Star **
Inefficiency Details & Impact
**
Inefficiency Details & ImpactWhy Optimize?
Gas Savings: The
**
operation consumes more gas compared to alternative constant value representations. By using optimized representations, you save gas on each transaction invoking these constants.
Practical Examples
Using type(uint256).max
Instead of 2**256 - 1
When you need to represent the maximum value for a uint256
, using type(uint256).max
is more efficient than calculating 2**256 - 1
.
Example:
Using 1e18
Instead of 10**18
For values derived from exponentiation with base 10, itโs more efficient to use the e
notation. For example, 1e18
should be used instead of 10**18
.
Example:
Recommendations for Efficient Representation
Avoid Double Star
**
for Common Constants: For commonly used constants, especially those involved with decimal representation, use thee
notation or thetype().max
where appropriate.Review and Refactor: Scrutinize your smart contract for uses of the
**
operator and evaluate whether an alternative representation would be more gas-efficient without sacrificing readability or accuracy.
Conclusion
Minor optimizations, like efficiently representing constant values, collectively contribute to gas-efficient smart contracts. While the individual savings per transaction might be minor, considering the frequency and volume of transactions on the Ethereum network, these optimizations are worth implementing. Always ensure to test your contract thoroughly after making these changes to validate that the contract behavior remains as expected while enjoying reduced gas costs.
References
Last updated