Skip to main content

Split Require Statements That Uses &&

Description

Splitting the require statements can make the code more gas efficient. When multiple conditions are checked with && in a single require statement, the gas cost can be high because all the conditions need to be evaluated even if the first one fails.

By splitting the require statements and checking each condition separately, the code can potentially save gas by not evaluating unnecessary conditions.

Example Code

Here is an example:

// Inefficient way
function transfer(address _to, uint256 _value) public {
require(_to != address(0) && _value > 0 && balances[msg.sender] >= _value);

balances[msg.sender] -= _value;
balances[_to] += _value;

emit Transfer(msg.sender, _to, _value);
}
// More gas efficient way
function transfer(address _to, uint256 _value) public {
require(_to != address(0));
require(_value > 0);
require(balances[msg.sender] >= _value);

balances[msg.sender] -= _value;
balances[_to] += _value;

emit Transfer(msg.sender, _to, _value);
}

Recommendation

It is recommended to split require statements when checking multiple conditions to potentially save gas costs.