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: