DEV Community

Rushank Savant
Rushank Savant

Posted on • Updated on

Variable sequence - 2

We previously saw in Variable sequence organization, that fitting multiple variables in single slot saves gas on execution.

But there is an exception to this case.
Lets just try to recall our previous observations, consider following contracts:

contract varSequence2_1{
    uint var1;
    uint var2;
    uint var3;

    function updateVar(uint num) external {
        var1 = num;
        var2 = num;
        var3 = num;
    }

}

contract varSequence2_2{
    uint8 var1;
    uint8 var2;
    uint8 var3;

    function updateVar(uint8 num) external {
        var1 = num;
        var2 = num;
        var3 = num;
    }

}
Enter fullscreen mode Exit fullscreen mode

Which contract will cost us more gas on updateVar function execution? If you guessed varSequence2_1 then you are right. This is similar to what we saw in Variable sequence organization.

Now, consider the following contracts:

contract varSequence2_1{
    uint var1;
    uint var2;
    uint var3;

    function updateVar(uint num) external {
        var1 = num;
    }

}

contract varSequence2_2{
    uint8 var1;
    uint8 var2;
    uint8 var3;

    function updateVar(uint8 num) external {
        var1 = num;
    }

}
Enter fullscreen mode Exit fullscreen mode

Which contract do you think will cost us more gas on updateVar function execution now? It will be varSequence2_2. But why so?

Conclusion

This is observed because the opcodes increase when you have to find a particular element and mask it out of a storage slot. And hence there is an increase in gas.

Top comments (0)