Normally there's no benefit to using different sub-types of uint
s (uint8
,Ā uint16
,Ā uint32
, etc.) because solidity reserves 256 bits of storage regardless of theĀ uint
Ā size. For example, usingĀ uint8
Ā instead ofĀ uint
Ā (uint256
) won't save you any gas.
But there's an exception to this: insideĀ struct
s.
If you have multipleĀ uint
s inside a struct, using a smaller-sizedĀ uint
Ā when possible will allow Solidity to pack these variables together to take up less storage.
Example ā
struct NormalStruct {
uint a;
uint b;
uint c;
}
struct MiniMe {
uint32 a;
uint32 b;
uint c;
}
// `mini` will cost less gas than `normal` because of struct packing
NormalStruct normal = NormalStruct(10, 20, 30);
MiniMe mini = MiniMe(10, 20, 30);
For this reason, inside a struct you'll want to use the smallest integer sub-types that will suffice for the struct.
Clustering ā
You'll also want to cluster identical data types together (i.e. put them next to each other in the struct) so that Solidity can minimize the required storage space. For example, a struct with fieldsĀ uint c; uint32 a; uint32 b;
Ā will cost less gas than a struct with fieldsĀ uint32 a; uint c; uint32 b;
Ā because theĀ uint32
Ā fields are clustered together.