1

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

1 Answer 1

2

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

1
  • Great answer thanks!
    – Kuly14
    Jul 15 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.