0

The Solidity Docs (v0.8.4) states:

The type byte[] is an array of bytes, but due to padding rules, it wastes 31 bytes of space for each element (except in storage). It is better to use the bytes type instead.

I couldn't find much info about this online. I've 3 questions:

  1. What are the padding rules in this case?
  2. What is considered as an 'element'?
  3. Is there an example of this?

1 Answer 1

3

The smallest addressable chunk of storage is a 32-byte word. Arrays lay out the elements in separate words in discrete locations, so each single-byte element will be in its own slot.

The smallest read/write op handles a full word even if many variables are packed in.

The compiler will pack them in if they "fit". This struct can read two variables in one SREAD:

struct TwentyOne {
  address a;
  bool b;
}

TwentyOne[] ;

"Array of bytes" has one word to store the length of the array, and one word for each element in the array. This is because it needs to be able to "jump" to a row. Consider that the memory is organized approximately like:

  • Length => EVM "slot": 3 (uint256 word)
  • row1 => EVM "slot": 1 byte, 31 wasted
  • row2 => EVM "slot": 1 byte, 31 wasted
  • row3 => EVM "slot": 1 byte, 31 wasted

A "slot" is always a 32-byte word and is the smallest unit of state storage that can be accessed.

Hope it helps.

3
  • so would: string a = "abcdefg" - create a 32-byte word for each character? In this case string a would consume 7 chunks of storage at 32 bytes each? Nov 26, 2021 at 10:13
  • @RobHitchens suppose i want to save the value 0xabcdef in a dynamic bytes array (not in bytes3), In this case also will it require one slot to store the data ? Also is another memory slot required to store the length value in case of dynamic byte array ?
    – amitKumar
    Dec 17, 2021 at 13:58
  • It will take four "words" so the elements can be accessed by row. Dec 17, 2021 at 17:39

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.