[Ethereum] Delete or clear a mapping

arraysmapping

From what I am gathering based on this question and this question it seems that I am better off not trying to clear arrays or mappings. As the documentation on mappings indicates every possible key is initialized upon declaration and mapped to zero values.

I've taken Nick Johnson's advice from the first Q and I'm keeping an array count which I'm using to iterate through the arrays (and mappings) in lieu deleting the arrays. My question is whether there's anything to be gained by clearing out the values associated with keys which are storing data.

One mapping is from an address to a list of structs, the other is from an address to a struct. Am I correct in thinking that the gas cost of storing the data is spent when it is set and thus there is no additional value in trying to free up space by clearing the struct data out?

Best Answer

Deleting a value in storage (one word - a struct may represent multiple words) gives a refund of 15,000 gas to the caller. As long as the number of elements you're clearing is well bounded (eg, it has a maximum for any single call), it's definitely worth reducing execution costs by deleting unwanted data. The exceptions are:

  • You need to free up an unbounded number of elements, in which case you may run out of gas while clearing storage.
  • You're likely to reset the same element to a new value later, in which case it's more gas efficient to not touch it than it is to clear and later re-initialize it.
Related Topic