Gas optimization Series Part - 3

Today, we'll see how you can save gas, by removing overflow checks in loops.

Solidity compilers perform various validations and checks during code execution, such as array bounds checking, integer overflow checking, and division by zero. These checks ensure that the code behaves as expected and prevents potential vulnerabilities.

But in some circumstances, we can reduce the gas cost by bypassing this check to reduce gas cost. For this, we use the "unchecked" keyword to inform the solidity compiler that the block of code should be executed without any checks. If used without precaution, this could bring serious security issues in the smart contract. Don't listen to me, listen to Uncle Ben.

Spidey Central

Now, let's see how we can easily utilize this power.

function increment()public {
    uint[] memory arr = new uint[](200);
    for(uint i=0; i < arr.length;i++){
    }
}

function uncheckedIncrement()public {
    uint[] memory arr = new uint[](200);
    for(uint i=0; i < arr.length;){
       unchecked {
           i++;
       }
    }
}

We start off with increments where "i" increments with checks and another function where "i" increments unchecked. We know arr length is 200, so "i" is never gonna overflow. Therefore we perform unchecked increment. Doesn't look much, does it? Let's see how much gas does that save us.

For, the first checked increment it cost us gas:

For, the second unchecked increment it cost us gas:

That's a significant improvement on gas.