โš–๏ธGas Saving Technique 6: NOT operator ! cheaper than boolean FALSE

Introduction

In the pursuit of optimizing smart contracts for lower gas consumption, every small improvement counts. One such micro-optimization involves using !true (logical NOT) instead of == false for boolean comparisons. This seemingly trivial change can lead to minor gas savings, contributing to the overall efficiency of your smart contract operations on the Ethereum network.

Impact & Details

Understanding Gas Consumption

  • Cost Differences in Comparisons: Using == false for comparison slightly consumes more gas than the !true approach. The == false comparison has an additional operation of checking equality, leading to a marginally higher gas cost.

Gas Savings with !true

  • Efficiency of Logical NOT: Utilizing !true is more gas-efficient as it directly negates the boolean value without the need for an equality check, offering a cleaner and more gas-conservative operation.

How to Implement !true for Gas Savings

Practical Example: Efficient Boolean Comparison

Letโ€™s understand this with a practical example:

Before Optimization:

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

contract BooleanOptimizer {
    bool public flag = true;

    function checkFlag() public view returns (bool) {
        if (flag == false) {  // Using == false for comparison
            return false;
        }
        return true;
    }
}

After Optimization:

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

contract BooleanOptimizer {
    bool public flag = true;

    function checkFlag() public view returns (bool) {
        if (!flag) {  // Using !true (logical NOT) for comparison
            return false;
        }
        return true;
    }
}

In the optimized version, !flag is used instead of flag == false. This makes the code not only more readable but also slightly more gas-efficient.

  1. Identify Boolean Comparisons: Review your smart contracts to locate boolean comparisons using == false.

  2. Use Logical NOT: Replace == false comparisons with !true to achieve minor gas savings per operation.

  3. Test: Implement thorough testing to ensure that the change maintains the expected contract behavior while saving gas.

Conclusion

While the gas savings from using !true instead of == false might appear minimal for a single transaction, it's important to consider the cumulative effect over thousands or millions of transactions. Such minor optimizations collectively lead to more gas-efficient smart contracts, ultimately resulting in lower costs for users and better resource utilization on the Ethereum network. Always ensure to test the smart contract extensively after making these micro-optimizations to validate that the functionality remains intact.

Reference

[G-09] Gas: Using the logical NOT operator ! is cheaper than a comparison to the constant boolean value false - NOT operator ! cheaper than boolean FALSE

Last updated