1

I have a couple of questions.

  1. we have int types as uint8, uint16, uint32, etc. I read that :

Normally there's no benefit to using these sub-types 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.

So If I type directly in the contract as state variable something like this:

  • uint8 test1;
  • uint32 test2;
  • uint test3;

Why won't uint8 test have less gas consumption wherever I use it than uint32 test2 ? I am asking because with uint8 test1 , I use less storage space.

  1. Let's say I use struct differently.
// way1
struct Person {
  uint8 test1;
  uint32 test2;
  uint8 test3;
}


// way2
struct Person {
  uint8 test1;
  uint8 test2;
  uint32 test3;
}

Why would the second way consume less gas than the first one ? If we look at the both struct, they both consume the same amount of storage, but still it's said way2 is gonna be much better for less gas consumption . Why ?

2

This is about how the variables are packed together and about how smart the compiler is (hint: not very smart). The compiler only tries to pack subsequent variables together but it can't pack variables which have something else between them.

In your first case the variables could all fit inside a single 32 byte slot, but if I'm not mistaken the compiler doesn't do that because they are of different types. In your second case the first two variables are of the same type and can be tightly packed inside one slot, therefore saving in gas.

You can read more about variable packing for example here: https://fravoll.github.io/solidity-patterns/tight_variable_packing.html

| improve this answer | |
  • So, if i don't use struct, and just have uint8 test1; uint8 test2; as the state(global) variables in contract, they (each one of them) use 32 byte slots separately even though they could have used the same slot, but still no, they use separate ones and in case of uint8(8 bits), 256-8 = 248 bits are just there doing nothing, correct ? so for state variables, i don't have to think about anything and I can just type uint all the time. if it's struct, that's where I have to think. agree ? – Nika Kurashvili Sep 29 at 13:22
  • This pattern works also for state variables. Quote from the link: "As hinted in the Applicability section, this pattern can be used for state variables, inside structs and for statically-sized arrays" – Lauri Peltonen Sep 29 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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