โœจ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

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

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

contract EfficientConstants {
    // Inefficient Representation
    // uint256 public constant MAX_UINT = 2**256 - 1;

    // Efficient Representation
    uint256 public constant MAX_UINT = type(uint256).max;
}

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:

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

contract EfficientExponents {
    // Before Optimization
    // uint256 internal constant SHER_DECIMALS = 10**18;

    // After Optimization
    uint256 internal constant SHER_DECIMALS = 1e18;
    uint256 internal constant SHER_STEPS = 1e16;
    uint256 internal constant RATE_STEPS = 1e4;
}

Recommendations for Efficient Representation

  1. Avoid Double Star ** for Common Constants: For commonly used constants, especially those involved with decimal representation, use the e notation or the type().max where appropriate.

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

[G-10] 10 ** 18 can be changed to 1e18 and save some gas

Last updated