Following answer and solidity_link says that:
Use delete on arrays to delete all its elements.
delete dataArray;
This is exactly the same as
dataArray.length = 0
From this answer as I understand that negative gas costs will be 15000.
The only two OPCODEs with negative gas costs are STORAGEKILL(-15000) and GSUICIDEREFUND(-24000).
[Q] Overall, after deleting an array; how much gas refund will be made? Would it be only 15000
or 15.000 * 'length_of_the_array'
?
=> For example, I have an array with length of 100. When I delete it how much gas will I be refunded?
If only 15000
; then should I traverse all the elements in an array and delete them rather than doing delete dataArray
?
Something like:
for (uint i=0; i< dataArray.length; i++) {
delete dataArray[i];
}
=> For example, if I want to delete an mapping that maps a struct (uint[]
that has 100 items), would it refund 15000
or the gas cost of the struct
that is pointed (15000 * 100
).
If only 15000
; then should I traverse all the elements mapped by the element as well and delete them rather than doing delete mappingData
?
mapping(address => uint[]) mappingData; //'0xabcd' maps to length of the `uint[]` is 100
delete mappingData;
Something like:
for (uint i=0; i< mappingData[0xabcd].length; i++) {
delete mappingData[0xabcd][i];
}
Some observation: If I traverse an delete and delete items one by one, traversing will charge me additional gas cost, maybe equivalent to the refunded gas so where would be the motivation to use delete
?
delete dataArray
/dataArray.length = 0
will also walk through the array and delete each removed element. So there should be no difference between the two in terms of the total gas refund.mapping
you would have todelete
individual values yourself, as there's no way to enumerate them automatically.