It seems that specifying something less than uint256
counterintuitively increases gas costs (or at best makes them equal to uint256 with optimization).
And since the minimum write to storage is 32 bytes (256 bits), it doesn't seem like specifying uint8
would necessarily save you gas either.
In what cases could one use uint<256
to save on gas?
One possible example: in a struct, if you group/list 8 uint32
variables together, would writing to those 256 bits (which presumably are stored consecutively in one word) be the same storage / gas cost as a single uint256
in the struct?
Best Answer
Your intuition on the struct is correct. It's efficient to write multiple uint<256 into a struct because of struct tight packing. According to the solidity docs,
Basically, it's efficient to use uint<256 inside of a struct (or an array). In these cases, you typically want use the smallest uint sizes you can get away with in order to keep the total struct size at or under 256bits.
I'm not sure if there are other examples where uint<256 is more efficient than uint, but I'm sure someone can think of something.