Skip to main content

Lower Gas Costing Operation First

Description

When using logical OR (||) or AND (&&) operators in Solidity, the order of the operations can impact the amount of gas used. When using these operators, the Solidity compiler generates code that evaluates the left operand, then conditionally evaluates the right operand based on the result of the left operand. If the left operand is true for an OR operation, or false for an AND operation, the right operand is not evaluated.

Therefore, it's best to put the lower cost operation on the left side, so that in the case where it already evaluates to the desired outcome, the more expensive operation is avoided altogether.

Example Code

Consider the following example, where we want to check if a given address is either the owner of a contract or a whitelisted address:

pragma solidity ^0.8.0;

contract Whitelist {
address public owner;
mapping(address => bool) public whitelist;

constructor() {
owner = msg.sender;
}

function isAllowed(address _address) public view returns(bool) {
return (_address == owner) || whitelist[_address];
}
}

In this code, we're using the OR operator to check if _address is equal to owner OR if it exists in the whitelist. By putting the cheaper operation first, if the address is already equal to owner, we avoid having to check the more expensive whitelist[_address] operation.

Recommendation

When using logical OR (||) or AND (&&) operators in Solidity, put the cheaper operation on the left side to avoid unnecessary gas usage. However, keep in mind that this optimization should not compromise the logic of the code or make it less readable. It's also important to test and verify the optimized code before deployment to ensure that it behaves as intended.