Sticking to uint256

Published by Mario Oettler on

Last Updated on 24. March 2025 by Mario Oettler

Before, we have learned to pack state variables in order to use as little storage slots as possible. But when doing this one should think about the size of the data. Using data shorter than 32 bytes (256 bits) can result in higher operation costs. The reason is that the EVM uses 256 bits internally. So, every variable with less than 256 bits length must be converted into a 256 variable. This costs a tiny amount of gas.

Look at the following lines of code.

pragma solidity 0.8.29;

contract conversion{
    uint16 public a;
    uint256 public b;

    function setA() public{
        a = 1;
    }

    function setB() public{
        b = 1;
    }
}

We can see, that we save eight gas units with every operation.

Categories: