Contents

Keyword 'Unchecked' for Gas Optimizaiton

Introduction

Before Solidity 0.8.0, the SafeMath library needed to be imported manually to prevent the data overflow attack.

In following Solidity version, solidity will perform a check every time data changes to determine if there is an overflow and thus decide whether to throw an exception.

This mechanism also brings additional gas consumption.

Therefore, solidity provides unchecked block modifier to effectively remove the intermediate overflow detection, achieving the purpose of gas saving.

In this unit testing, I run unchecked block and without unchecked block 1000 times to evaluate the gas consumption.

We list code of contract as follow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Unchecked {

    uint public res;

    function withoutUnckecked(uint256 times) external {
        uint result;
        for (uint256 i; i < times; i++) {
            result = i + 1;
        }
        res = result;
    }

    function withUnckecked(uint256 times) external {
        uint result;
        for (uint256 i; i < times; ) {
            unchecked {
                result = i + 1;
                i++;
            }
        }
        res = result;
    }
}

Evaluation

Here is the result:

MethodGas FeeNet Gas FeeSave(Compare to writeByCalldata)
withoutUnckecked4157514157510
withUnckecked113773113751302000 (≈73%)

Conclusion

If the security is under control, it is recommended to utilize unchecked for gas optimization.