1

Consider im having to deal with 3 uint8 values each of which are to be stored for each user. Is the gas cost the same if i use 3 different arrays or if i use a structure array which contains the 3 uint8 values together.

struct Users{
  uint8 no1;
  uint8 no2;
  uint8 no3;
}
Users[] public users;

Thanks

3

Is the gas cost the same if i use 3 different arrays or if i use a structure array which contains the 3 uint8 values together.

In your example, the three uint8 would be packed into a single 32-byte word.

    struct Users{
      uint8 no1;
      uint8 no2;
      uint8 no3;
    }

Notice the array:

Users[] public users;

So, you have users[0], users[1], users[2} .... Each would return a single struct that happens to contain 3x 8-bit uint8.

if i use 3 different arrays

uint8[] no1;
uint8[] no2;
uint8[] no3;

To fetch or store 3, it would look something like:

uint8 a = no1[0]; uint8 b = n02[0]; uint8 c = no3[0];

Each uint8 is individually addressable and we had to do three ops to get all three. Each one is using an entire 32-byte word because that is the smallest unit of addressable space.

We also had to do it in three steps instead of one step. So, there will be more operations to step through it. By far, the most expensive ops will be the writes. The first way, using struct, prepares a single SSTORE to one "slot" (5-20K gas). The separate arrays technique prepares three SSTORE ops to three slots (15-60K gas).

Hope it helps.

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.