Solidity – Efficient Struct Ordering for Less Gas Consumption

soliditystatestruct

Unlike initializing state variables in specific orders in order to save on gas, does this also apply to how you declare your struct properties where you keep lower uints side by side each other?

// State arranged to save gas
contract Foobar {
    uint8 foo;
    uint8 bar;
    uint16 baz;
    uint num;
}

// Does the same concept apply to a struct as well?
struct Item {
    uint8 foo;
    uint8 bar;
    uint16 baz;
    uint num;
}

Or can you go all crazy in the struct and type it in any order?

Best Answer

If you are refering to struct stored in storage then yes, the very same rules apply as described in the documentation :

  • The first item in a storage slot is stored lower-order aligned.

  • Value types use only as many bytes as are necessary to store them.

  • If a value type does not fit the remaining part of a storage slot, it is stored in the next storage slot.

  • Structs and array data always start a new slot and their items are packed tightly according to these rules.

  • Items following struct or array data always start a new storage slot.

In memory however, every element is stored on 32 bytes, except for bytes and string as you can see here.

Related Topic