Packing Structs

Published by Mario Oettler on

Last Updated on 24. March 2025 by Mario Oettler

It is also possible to apply the packing of variables to structs by placing their fields in the correct order.

Example

This code shows an unpacked struct in Solidity.

pragma solidity 0.8.29;

contract StrucktUnPacked{
    struct myStruct{
        uint128 varA;
        uint256 varB;
        uint64 varC;
    }

    myStruct varD = myStruct(1, 2, 3);

    function getVariables() public returns(myStruct memory){
        return varD;
    }
}

This code shows a packed struct in Solidity.

pragma solidity 0.8.21;

contract StrucktPacked{
    struct myStruct{
        uint128 varA;
        uint64 varB;
        uint256 varC;
    }

    myStruct varD = myStruct(1, 2, 3);

    function getVariables() public returns(myStruct memory){
        return varD;
    }
}

The following table shows the gas cost for deployment including variable setting and variable reading.

Deployment incl. setting variablesReading variables
Unpacked27339230259
Packed24826532502

As we can see, reading from a packed struct can be more expensive than reading from an unpacked struct. However, writing to it is cheaper.

Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: