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 toa
, i.e. it stores a new object ina
.
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:
validAddresses[x] = false;
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.