๐ชGas Saving Tutorial 27: Efficient Boolean Comparison
Introduction: In smart contract development, every bit of gas saved is crucial, especially for functions that get called frequently. One common micro-optimization that often goes unnoticed is how boolean values are compared. In this tutorial, we'll show you how to make your boolean comparisons more gas-efficient in Solidity.
Concept: Booleans inherently represent true
or false
. Comparing them directly to true
or false
is redundant and slightly gas inefficient. Rather than using if (booleanValue == true)
, you can simply use if (booleanValue)
. For false checks, instead of if (booleanValue == false)
, if (!booleanValue)
can be used.
Benefits include:
Gas Efficiency: Avoiding the direct comparison conserves some gas as fewer opcodes are executed in the EVM.
Code Clarity: Directly using the boolean value usually results in more readable and concise code.
Example:
Given the code snippet in a governance system:
solidityCopy codefunction voteOnProposal(uint256 proposalId)
external
onlyRegisteredVoter
{
require(
hasVoted[msg.sender][proposalId] == false, //@audit gas: instead of comparing to a constant, just use "hasVoted[msg.sender][proposalId]"
"Voter has already voted on this proposal!"
);
...
}
The optimized boolean comparison would be:
solidityCopy codefunction voteOnProposal(uint256 proposalId)
external
onlyRegisteredVoter
{
require(
!hasVoted[msg.sender][proposalId], // Simply negate the boolean value for a false check
"Voter has already voted on this proposal!"
);
...
}
Recommendation:
Examine your contracts for boolean comparisons using
== true
or== false
.Replace these direct comparisons with the efficient boolean evaluations.
Test to make sure the logic remains consistent and the behavior is as intended.
Conclusion:
Though the savings from boolean comparison optimizations might seem minute, they add up to provide a more gas-efficient and cleaner codebase. In projects with a multitude of such comparisons, the aggregated savings over numerous transactions can be significant. Always aim for efficient, clean code that accomplishes the same objective with fewer operations.
Last updated