โœ’๏ธGas Saving Technique 21: Unneeded If statements

Introduction

Every operation in a smart contract costs gas. To optimize for lower gas consumption, it is crucial to remove code that doesn't contribute to the contractโ€™s functionality. One common area of improvement is the removal of unnecessary if statements that check conditions already verified elsewhere or conditions that can never be true. This tutorial will guide you through identifying and removing such redundant if statements.

Impact & Details

Understanding the Impact:

  • Gas Savings: Unnecessary if statements waste gas each time the contract is called, and removing them can lead to gas savings over the lifetime of the contract.

  • Code Simplification: Redundant checks complicate the codebase. Removing them simplifies the code, making it easier to read and maintain.

Example: Removing Unneeded 'If' Statements

Before Optimization:

solidityCopy codepragma solidity ^0.8.0;

contract ExampleContract {
    function cleanUp(bytes32 claimIdentifier) external {
        if (_setState(claimIdentifier, State.NonExistent) != State.Cleaned) {
            revert InvalidState();  // This check might be unnecessary
        }
        // ... rest of the function ...
    }
}

After Optimization:

Analyzing the _setState function and understanding the various states a claimIdentifier can be in will often reveal that some checks are unnecessary. If you find that _setState(claimIdentifier, State.NonExistent) can only result in State.Cleaned or revert beforehand, you can safely remove the if statement.

solidityCopy codepragma solidity ^0.8.0;

contract ExampleContract {
    function cleanUp(bytes32 claimIdentifier) external {
        _setState(claimIdentifier, State.NonExistent);
        // The unnecessary 'if' statement has been removed
        // ... rest of the function ...
    }
}
  1. Review and Analyze: Review the code thoroughly to identify if statements that check for conditions already verified elsewhere or that will never be true.

  2. Remove Redundant Checks: After identification, safely remove these unnecessary if statements from the code.

  3. Test: Always test the contract after making changes to ensure that it still behaves as expected.

Conclusion

Removing unneeded if statements is a simple yet effective optimization that can lead to gas savings and a cleaner, more manageable codebase. Always be sure to understand the logic and states of your contract thoroughly to safely remove these checks without introducing new risks, and test your contract extensively to ensure it behaves as expected after the changes.

Last updated