[Ethereum] Delete an entry in a mapping

mappingmemorysolidity

To my understanding, delete x merely sets the value of x to the default value defined for the type of x (which is typically 0 in one way or another).

For example:

uint x = 1;
delete x; // sets x = 0

bool x = true;
delete x; // sets x = false

The doc actually says it pretty explicitly:

It is important to note that delete a really behaves like an assignment to a, i.e. it stores a new object in a.

But my question is really with regards to mappings.

Suppose I have mapping (address => bool) validAddresses and some address x.

Are the following two statements equivalent:

  1. validAddresses[x] = false;
  2. delete validAddresses[x];

Or is there any benefit in #2 over #1 (as there would be in "traditional" languages)?

The doc states something which might answer my question:

delete has no effect on whole mappings (as the keys of mappings may be arbitrary and are generally unknown).

But I'm honestly having problems understanding it.

I do understand that delete has no effect on anything other than mappings, in the sense that no memory is being freed as a result of executing it.

But I do not understand whether or not the same thing applies for mappings.

UPDATE:

I went ahead and disassembled each one of these two statements via solc --asm.

Statement #1:

    /* "contracts/MyContract.sol":1490:1538  validAddresses[x] = false */
  dup1
  sload
  0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
  and
  swap1
  sstore

Statement #2:

    /* "contracts/MyContract.sol":1490:1537  delete validAddresses[x] */
  dup1
  sload
  0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
  and
  swap1
  sstore

The compiled code indicates that the two statements are identical, so I'm basically just looking for a confirmation on this fact (in opposed to the answer below, which suggests that gas-refund applies only when delete is used explicitly).

Best Answer

When you use the delete operation, rather than assigning to 0, you get a 10000 gas refund.

Update

It appears you are correct, and that the refund doesn't matter whether you zero the variable or use delete.

I tested the following contract in remix, and the transaction and execution costs of the d and c functions are nearly identical, although the function which uses delete used 104 less gas. I'm not sure what accounts for this.

pragma solidity ^0.4.20;

contract T{
    mapping (address => bool) validAddresses;
    function set() external{
        validAddresses[0xca35b7d915458ef540ade6068dfe2f44e8fa733c] = true;
    }
    function c() external{
        validAddresses[0xca35b7d915458ef540ade6068dfe2f44e8fa733c] = false;
        //tx 13409
        //ex 5545 
    }
    function d() external{
        delete validAddresses[0xca35b7d915458ef540ade6068dfe2f44e8fa733c];
        //tx 13374
        //ex 5476
    }
}
Related Topic