Solidity Gas Optimization – Why and When to Use uint8 Instead of uint?

gasopcodeoptimizationsoliditystate-variable

As far as I know uint8 costs more gas than uint256 (or uint they are same).

Let's say my variable can't be bigger than 100, and I already check for it with an if statement.

I saw many examples of uint8 usage instead of uint and they say "optimization". If uint8 costs more gas than uint256, isn't it "inefficient" to make it uint8?

Best Answer

If you just have one uint8 then yes, it will cost more gas than using a uint256 because its data needs to be padded to fit a word which takes 256 bits. So it takes the same amount of storage but costs more because of the padding.

But the magic happens when you have more than one uint8 declared next to each other. In that case they can be stored inside one word slot and therefore take less space. In theory you can therefore store 256 / 8 = 32 of these in one slot, but there is possibly some overhead and not that many fit - unsure.

When I said declared next to each other it means that they can't be packed if there is for example and address between them.

So using uint size smaller than 256 is useful only if you store more of those in the same slot - otherwise it just costs more than uint256.

You can read more about variable packing here.

Related Topic