2

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?

1 Answer 1

4

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.

2
  • By "declared next to each other" do you mean to use inside the same struct or just declaring variables in lines next to each other is enough? I understand from the link you shared thay I need to declare them inside a struct. Thanks btw, this is the most logical explanation of why to use small byte variables.
    – Yetik
    Commented Oct 19, 2022 at 14:11
  • I don't think they need to be inside a struct, but not 100% sure. And "next to each other" means that there is no other code between them. Commented Oct 19, 2022 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.