10

My understanding is that the mapping type cannot be used as a local variable, and must be a member (i.e., state) variable.

Is there a conceptual reason for this to be the case? I can't imagine this couldn't be implemented as a memory variable?

1 Answer 1

18

You are correct that there is no fundamental reason why mappings couldn't be done in memory, but the implementation would have to be very different from those in storage.

In storage, as described in this excellent article, the storage location of an element is indexed by a hash of the key, plus maybe some other stuff. This works really well for storage, which under the hood is fundamentally a key=>value store as implemented by the EVM.

Memory, however, is organised differently. Memory locations are indexed sequentially from zero in bytes. If you write to (or read from) a memory location with non-zero index then all the memory up to that index is allocated and charged for in gas. So if you touch only memory location 1000, you get charged for 1000 bytes (1024 to be precise). The gas cost of memory allocation increases quadratically with the size allocated, so it soon becomes expensive.

Thus, writing to Memory[keccak256(key)] is basically unfeasible - it would allocate a huge amount of empty memory all the way up from zero to the key's 256-bit hash value. In all likelihood an enormous cost.

To do mappings in memory, then, would need implementation of a tightly memory-bounded key=>value store. These exist, but are not implemented by the Solidity compiler so far.

3
  • 2
    Thanks @Benjaminion. So, the EVM maintains a trie anyways, so therefore adding mappings doesn't really add overhead in the form of setup because the system already has a trie to append to. However, if you formed a trie in memory, you would have all of the overhead of creating the trie, and that's prohibitive and why it hasn't been done yet? Is that a fair description?
    – pfrank
    Commented Sep 7, 2017 at 17:02
  • Great answer... this is really screwing me up though...
    – Alex
    Commented Feb 16, 2018 at 5:25
  • 1
    @Benjaminion, is it still true today? I run an experiment and found Memory[keccak256(key)] doesn't cost significantly higher amount of gas than normal.
    – Maxareo
    Commented Mar 11, 2021 at 1:24

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.