Consider the following two Solidity structs. Which one will generally consume less gas when stored on-chain?
struct A {
uint256 a;
uint256 b;
bool c;
}
struct B {
uint128 a;
uint128 b;
bool c;
}Think about how Solidity packs variables into 32-byte storage slots.
Solidity packs smaller variables together to fit into a single 32-byte storage slot. Struct B uses uint128 and bool, which can be packed tightly, reducing storage slots and gas costs. Struct A uses two uint256 variables which each take a full slot, wasting space.
Given this Solidity struct, how many 32-byte storage slots will it occupy?
struct Data {
uint8 a;
uint16 b;
uint256 c;
bool d;
}Remember that Solidity packs variables tightly if they fit in the same 32-byte slot.
uint8 a (1 byte) and uint16 b (2 bytes) pack into slot 0. uint256 c (32 bytes) uses slot 1. bool d (1 byte) uses slot 2. Total: 3 slots.
Analyze the following Solidity code snippet. Why does the gas cost remain high despite packing variables?
struct Packed {
uint128 a;
uint256 b;
uint128 c;
}Consider how storage slots are allocated in order.
uint256 b occupies a full 32-byte slot, so the uint128 variables before and after it cannot be packed together. This causes inefficient storage and higher gas.
You have these variables to store in a struct: uint64 x;, bool y;, uint256 z;, uint32 w;. What order should you declare them to minimize gas?
Group smaller variables together before larger ones.
Smaller variables (uint64, uint32, bool) should be declared first to be packed into one slot. The large uint256 should be last to occupy its own slot.
Given this Solidity contract snippet, what is the value of slot after execution?
contract Test {
struct S {
uint128 a;
uint128 b;
uint256 c;
}
S public s;
function getSlot() public pure returns (uint) {
uint slot;
assembly {
slot := s.slot
}
return slot;
}
}State variables are assigned storage slots starting from 0 in order.
The struct s is the first state variable, so its storage slot is 0. The assembly code correctly reads s.slot which is 0.