DEV Community

Rushank Savant
Rushank Savant

Posted on • Updated on

Short-circuiting

The basic intention behind using Short-circuiting in any coding language is to reduce the number of computations done during comparison operations. And in solidity, reduced computations means reduced gas.

Consider the following contracts:

contract shortCircuit1 {
    bool flag;

    function conditions(int x) external {
        bool isEven = x % 2 == 0;  // computation 1
        bool isNotZero = x != 0;   // computation 2

        if (isEven && isNotZero) { // computation 3
            flag = true;
        } else {
            flag = false;
        }
    }
}


contract shortCircuit2 {
    bool flag;

    function conditions(int x) external {

        if (x % 2 == 0 && x != 0) { // 3 computations only if x % 2 == 0 is true, else only 1 computation
            flag = true;
        } else {
            flag = false;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Both the contracts follow same conditions, input to function should be even and greater than 0. If the conditions are true, then the state variable flag is set to true. And if previous function call made flag true and the next call do not satisfy both conditions then flag is set to false.
Now let's just focus on the conditions written inside the functions.

shortCircuit1
function input - 0
computes both the conditions and then performs 3rd computation to checks if both conditions are true.

Image description

shortCircuit2
function input - 0
computes second condition only if first condition is true (short-circuit). Hence saving the cost of computation.

Image description

Note:- The difference in gas is very less for the examples given above. Imagine a lengthy comparison computation (say a string or array), in such cases the gas difference will be significant.

Top comments (0)