3

Tight variable packing is a known coding pattern in Solidity for saving gas by placing variables that are lower than 256 bits closer to one another in structs.

For instance, the following will cost only one EVM word rather than two:

struct MyStruct {
    uint128 a;
    uint128 b;
}

However, does the same hold true for dynamic types like array where the type of the array has less than 256 bits?

struct MyStruct {
    uint128 a[];
}

Would this result in tight packing if I insert two elements in the array, or nah?

2 Answers 2

2

According to the docs, struct types and array types will always pack the elements tightly to save storage space. You can read about it more on here

2

From the docs:

Except for dynamically-sized arrays and mappings (see below), data is stored contiguously item after item starting with the first state variable, which is stored in slot 0.

Source: https://docs.soliditylang.org/en/v0.8.16/internals/layout_in_storage.html#:%7E:text=structs%20and%20array%20data%20always%20start%20a%20new%20slot%20and%20their%20items%20are%20packed%20tightly%20according%20to%20these%20rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.