DEV Community

Rushank Savant
Rushank Savant

Posted on ā€¢ Edited on

4 3

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.

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

Top comments (0)

šŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay