👂Gas Saving Technique 30: Using 1 and 2 rather than 0 and 1 saves gas
Introduction: Solidity is a unique language with many nuances that can affect gas consumption. One such nuance involves the representation and usage of integer constants. This tutorial will dive into why using 1 and 2 as constant values can be more gas-efficient than 0 and 1.
Concept: In Ethereum, the EVM (Ethereum Virtual Machine) treats the integer value 0 differently, as it's the default value of storage slots. When a storage slot is set to 0, the EVM refunds some gas because it assumes that you're freeing up storage. However, if you're using 0 and 1 for flagging or other logical purposes and not for freeing storage, this gas refund is not beneficial. Moreover, setting a value to 1 costs slightly more than setting it to any other non-zero value. Therefore, using 1 and 2 (or any other pair of non-zero values) can be more gas-efficient.
Underlying Problem:
Unnecessary Gas Refund: Using
0as a logical constant can trigger gas refunds, which are counterproductive if the intention isn't to free up storage.Higher Cost for
1: Setting a value to1in storage is slightly more expensive than setting it to other non-zero values.
Examples & Recommendations:
DepositHandler Constants:
Before:
solidityCopy codeuint256 internal constant IS_NOT_LOCKED = uint256(0); uint256 internal constant IS_LOCKED = uint256(1);After:
solidityCopy codeuint256 internal constant IS_NOT_LOCKED = uint256(1); uint256 internal constant IS_LOCKED = uint256(2);
Step-by-Step Guide to Implementing the Integer Gas Saving Technique:
Review your contract for instances where
0and1are used as logical constants or flags.Change those constants to
1and2respectively.Ensure that any conditional checks or logic that relied on these constants are updated accordingly.
Test the modified contract thoroughly to ensure consistent functionality.
Benefits:
Gas Savings: By avoiding the default storage value (
0) and the slightly higher cost of1, contracts can conserve gas over multiple transactions.Clearer Intention: Using
1and2makes it clear that these values are being used for logic, not for storage clearing.
Conclusion: Solidity, with its ties to the Ethereum ecosystem, has many peculiarities that can influence gas costs. Understanding these intricacies, like the special treatment of integer values 0 and 1, allows developers to write more optimized and efficient contracts.
Last updated