Variable sequence organization.

rushanksavant

Rushank Savant

Posted on May 2, 2022

Variable sequence organization.

The sequence in which we we define our state variables in solidity smart contracts affects the gas fees we spend while contract deployment as well as while calling functions that make use of those variables.

Solidity stores state variables in 256 bits slots, and if 2(or more) consecutive variable sizes add up to 256 or less, then these variables are stored in same slot. (types like bytes can acquire upto 2 slots)

Let's experiment using following contracts:

contract varSequence_1{
    uint128 var1;
    uint256 var2;
    uint128 var3;
    byte

    function set(uint num1, uint128 num2) external {
        var1= num2;
        var2= num1;
        var3= num2;
    }
}
Enter fullscreen mode Exit fullscreen mode
contract varSequence_2{
    uint128 var1;
    uint128 var3;
    uint256 var2;

    function set(uint num1, uint128 num2) external {
        var1= num2;
        var2= num1;
        var3= num2;
    }
}
Enter fullscreen mode Exit fullscreen mode

Both the contracts are exactly same, just the sequence of defining variables is changed.

Results:

Deployment costs

  • varSequence_1

Image description

  • varSequence_2

Image description

There is very minor difference in deployment, let's check the function calls.

Function call costs

  • varSequence_1

Image description

  • varSequence_2

Image description

Observation

varSequence_2, which had optimized variable sequence costed almost 25% less than varSequence_1.

💖 💪 🙅 🚩
rushanksavant
Rushank Savant

Posted on May 2, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Variable sequence - 2
solidity Variable sequence - 2

May 13, 2022

Loop increments
solidity Loop increments

May 5, 2022

Short-circuiting
solidity Short-circuiting

May 4, 2022