5

I know that you can have up to 2^256 entries in a single mapping.

However, if I am creating a mapping(address => mapping(uint => uint)), then does it mean that the inner mapping can also contain 2^256 entries?

1 Answer 1

7
+100

Consider a 2-dimensional mapping mapping(uint256 => mapping(uint256 => uint256)) m;

You could insert 2256 values into m[0][0], m[0][1], ..., m[0][2 ** 256 - 1]. But there are “only” 2256 storage slots in the EVM, so if you proceeded to insert a further 2256 values into m[1][0], m[1][1], ..., m[1][2 ** 256 - 1], they would overwrite all the others.

Multi-dimensional mappings are just an illusion. When you access m[k1][k2], Solidity translates it into slot[f(k1, k2)]. So all 2256 × 2256 = 2512 possible combinations of k1 X k2 will have to map onto 2256 storage slots, so there are going to be many dogs for the same bone, so to speak. The good news is that 2256 is such an inconcievably large number that the probability of accessing two mapping values whose storage slots collide is inconcievably small, so in practice the illusion will never be broken and you don’t need to worry about it.


f(k1, k2) = keccak256(k2 . keccak256(k1 . p)), where p is 0 if the mapping is declared as the first storage variable, 1 if second, etc. More info in the docs.

0

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.