1

Is it common that dictionaries like mapping(uint => uint) foo; cannot be cleared with something like clear()? What is the reason deleting mappings aren't allowed in Ethereum?

2

Ethereum / solidity does not allow the clearing of mappings because mappings do not inherently keep track of the keys. A user would be required to provide the key for each used spot in the mapping to be removed. Additionally, when you 'delete' or clear each key's value, you are really just setting this key value back to it's default value (zero in many cases). This means that you are writing to storage, which has a relatively high cost. If you had a large mapping to delete, it could be a costly operation.

documentation on clearing mappings

There are Iterable Maps which could make this functionality a bit easier by tracking keys, however deleting all key-value pairs could still remain costly.

This idea of cost for functionality is what makes executing logic on the ethereum different from traditional programming and is why clearing a mapping impractical. To interact with a smart contract, the user must pay for the transaction based on the amount of gas consumed when executing the code called in the smart contract. The cost of a transaction is determined by the gas cost of the OpCodes that are used. As you can see from the gas cost per Opcode, most are relatively low cost - however the functionality of reading from storage (sload) is relatively expensive and writing (sstore) to storage is very expensive. When setting a basic value in a mapping back to it's default (0), you do receive a 15000 gas refund, however the sstore costs 20,000 and the refund cannot be used toward the transaction that is being executed.

  • what does it look like in other languages? without requiring you to go into extreme detail, it seems like clearable mappings/dictionaries are not too uncommon. I was wondering about what the difference is, so I could understand it in context to what other standards are common. – postAsAGuest Jan 25 at 23:28
  • updated the answer a bit to describe why comparing creating code that will execute on ethereum is different than writing traditional code - this is why there is not functionality to clear a mapping. You could pretty quickly write the code to do it, but it would be very costly very quickly. – Steven V Jan 25 at 23:46

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.