7

I have been wondering as to what benefits we get from deleting elements from a storage array in ethereum contracts ?

That particular state is already in a block isn't it ?

Could someone please explain if it's a good practice to delete elements from storage arrays and if not why ?

5

Yes, it's a good practice. The tangible benefit is that it refunds gas. Deleting something (setting it to zero from non-zero) costs 5,000 gas but gives you a 15,000 gas refund. The gas refund is applied at the end of the transaction and can subtract up to half of the transaction's gas cost.

  • Thanks for the quick response. If I use delete to delete an array element and does not resize it (like copying the last element to the deleted slot and decreasing the length), would that save space as well ? – psaw.mora Mar 19 '18 at 17:02
  • Yes. Storing a zero in any storage slot that used to be non-zero saves space and gives you a gas refund. – user19510 Mar 19 '18 at 17:04
  • So the only benefit of reordering is just to keep the length and actual element count the same (For some functional benefit) ? What if like we have a 1000 element array and delete about 999 elements. Then the length would be shown as still 1000 but the actual element count would be 1. – psaw.mora Mar 19 '18 at 17:09
  • Yes. (It would particularly help if you need to enumerate the array.) – user19510 Mar 19 '18 at 17:10
  • Got it. Thanks and is there any documentation explaining how EVM internally handles memory ? – psaw.mora Mar 19 '18 at 17:13
1

Iterating through an array can get expensive, each element you access costs 200 gas. It's in your best interest to keep your array as small as possible and manage its size. Additionally, you get a net gas refund of 10,000 as smarx answered, which can help offset other processing that you may be doing.

1

Deleting slots from the storage will make a fast or light syncs faster for the nodes, since the snapshot of the contract's state at a block after your delete will be smaller. Moreover, you'll get a refund for deleting a storage slot (it costs 5000, but you'll get a refund of 15.000 at the end of the transaction, max. up to 50% of transaction's gas cost). For maximum efficiency clearing the storage should not be called as a separate transaction, but always be combined with another business operation.

1

For the freed of the storage memory cell (256 bit) you will get 10000 gas. Actually, you get 15000 gas as a refund for freeing storage cell, but the price of using SSTORE (modify storage cell) is 5000, so that you get 15000 - 5000. You can read about it in details in ethereum yellow paper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.