4

Say, I declare a mapping that uses uint256 numbers as keys and maps them to a single 8 bit character. I add 5 members to this mapping.

Obviously, I can then access any of these 5 characters using their respective indices.

So what I wanna know is, does this mapping consume 5*8 = 40 bits of memory or 5*8 + 5*256 = 1320 bits?

1 Answer 1

3

A mapping is dynamic type working as a storage (not memory) key-value database

let's take the following example

contract C {
    mapping(uint256 => uint256) items;
    function C() {
      items[0xC0FEFE] = 0x42;
    }
}

The assembly code for C function will contain :

  // Storing 0x42 to the address 0x798...187c
  0x42
  0x79826054ee948a209ff4a6c9064d7398508d2c1909a392f899d301c6d232187c
  sstore

which means we store the value 0x42 in the value corresponding to the key 0x79826054ee948a209ff4a6c9064d7398508d2c1909a392f899d301c6d232187c which is the hash of the mapping key 0xC0FEFE

here's an interesting discussion about why mapping could not be designed for memory usage Why (conceptually) can't mappings be local variables?

4
  • Does that effectively mean that the indexes won't occupy any storage since they are only being used to assign a storage address to the value? Sorry if it sounds dumb(I'm fairly new to ethereum) but does that mean the example mentioned in the question will infact only only consume 40 bits of storage?
    – Sc4R
    Commented Aug 7, 2019 at 0:18
  • 1-yes 2-in this example we store only 1 byte
    – Badr Bellaj
    Commented Aug 7, 2019 at 8:56
  • Isn't it stored the value 0x0000000000000000000000000000000000000000000000000000000000000042 since slots are 32 bytes?
    – Ismael
    Commented Aug 14, 2019 at 16:17
  • Exactly each value is 32-bytes wide. but initially its only a 1 byte. it's like storing 1 byte in an array with a size of 32 byte (in my comment i was talking about the size in the entrypoint)
    – Badr Bellaj
    Commented Aug 14, 2019 at 16:26

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.