Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use uint256 instead of uint8 in loops #5

Open
cleanunicorn opened this issue Aug 8, 2022 · 0 comments
Open

Use uint256 instead of uint8 in loops #5

cleanunicorn opened this issue Aug 8, 2022 · 0 comments

Comments

@cleanunicorn
Copy link
Member

cleanunicorn commented Aug 8, 2022

Description

The EVM works with 256bit/32byte words. For smaller data types, further operations are performed to downscale from 256 bits to the required lower bites type, and therefore having uint8 as an iterator consumes more gas than keeping it to uint256.

pragma solidity ^0.6.12;

/**
 * Show the difference in gas costs between a loop that uses a uint8 variable
 * and one that uses uint256 variable.
 * 
 * Both contracts compiled with `Enable Optimization` set to 200 runs.
 */

contract LoopUint8 {
    
    address[] internal arr;

    // 1st call; arr.length == 0: gas cost 42719
    // 2nd call; arr.length == 1: gas cost 30322
    // 3rd call; arr.length == 2: gas cost 32925
    function add(address _new) public {
        for (uint8 i = 0; i < arr.length; i++) {
          if (arr[i] == _new) {
            require(false, 'exists');
          }
        }
        
        arr.push(_new);
    }
}


contract LoopUint256 {
    
    address[] internal arr;

    // 1st call; arr.length == 0: gas cost 42713
    // 2nd call; arr.length == 1: gas cost 30304
    // 3rd call; arr.length == 2: gas cost 32895
    function add(address _new) public {
        for (uint256 i = 0; i < arr.length; i++) {
          if (arr[i] == _new) {
            require(false, 'exists');
          }
        }
        
        arr.push(_new);
    }
}

Recommendation

Use uint256 for the loop iterators.

@cleanunicorn cleanunicorn changed the title Use uint256 instead of uint8 Use uint256 instead of uint8 in loops Aug 10, 2022
@cleanunicorn cleanunicorn removed the WIP label Aug 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant