Solidity – How Much Gas Does Overflow Check Cost?

gassolidity

From solidity 0.8.x the compiler automatically checks for overflows and underflows. This costs additional gas.

My question is how much gas it costs and how much you can save by using the unchecked {}.

Thanks

Best Answer

I have tested the following smart contract with an optimization of: 200000

contract TestGasCostUnchecked {    
    uint256 a;
    function add() external{
        unchecked {
            a = a + 1;
        }
    }
}

executing the function add in remix result in a gas cost of: 43289

contract TestGasCost {    
    uint256 a;
    function add() external{
        a = a + 1;
    }
}

executing the function add in remix result in a gas cost of: 43362

as you can see the difference is the "unchecked" and this resulted in a difference of: 73 unit of gas


here you have another example:

contract TestGasCost {    
    function add(uint256 _value) external returns(uint256){
        return _value + 1;
    }
}

gas cost: 21531

contract TestGasCostUnchecked {    
    function add(uint256 _value) external returns(uint256){
        unchecked {
            return _value + 1;
        }
    }     
}

gas cost: 21445

For this example the difference in terms of gas is: 86

Related Topic