Solidity Gas Uint256 – Better Practices for Using Smaller uint Sizes When Applicable

gassoliditytimeuint256

My understanding of uint sizes is that smaller sizes will decrease gas costs. In my current dapp I'm building, I am dealing with time, for which it seems that uint32 will be plenty for my purposes (136 years if the time is stored in seconds).

Is it standard practice to use the maximum uint size in Solidity development or should applications be designed with the plausible int range in mind and use smaller sizes where applicable.

Best Answer

It really depends on the way you implement it. EVM allocates you new memory slots in 256 bit chunks and in order that the state variables are declared.

So if you declare them like that:

uint32 time;
uint256 money;
uint32 anotherTime;

these variables will take up 3 slots of 256 bit: time will create a first 256 bit slot and take 32 bit in it, money will not fit in the remaining bits in this slot so it will create a new 256 bit slot and fill it all, and anotherTime will create a new slot of 256 bit. On the other hand,

uint32 time;
uint32 anotherTime;
uint256 money;

this will only take 2 slots, as time and anotherTime can be compressed into one slot by the compiler.

Related Topic