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?
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.
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.