1

I needed a way to clear a storage array in my contract. I've seen this answer, but I tried to think of different approach (My arrays are most probably will contain enormous amount of elements) and have come up to this.

I create empty storage array of the same type, as the array I want to clear. Then I just assign empty array to filled array. Here is contract I used for testing.

pragma solidity ^0.4.18;

contract Test {
    address[] array;
    address[] helper;

    function Test() public {
        array.push(0x0);
        array.push(0x0);
        array.push(0x0);
        array.push(0x0);
    }

    function getSize() public view returns (uint256) {
        return array.length;
    }

    function clear() public {
        array = helper;
    } 
}

It works as intended, getSize() returns 0 after I call clear().

So now I wonder, if there are some hidden problems in this approach, including something like "dangling pointers" or increased gas cost.

Thank you in advance.

3

After reading docs about types thoroughly, I found that calling delete on dynamic array frees all allocated memory.

delete a assigns the initial value for the type to a. I.e. for integers it is equivalent to a = 0, but it can also be used on arrays, where it assigns a dynamic array of length zero or a static array of the same length with all elements reset.

Internally, calling delete on array assigns it to a new empty array, like I did.

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

Transaction cost is lower for delete call, than for manual assignment to empty array (not speaking about storing this empty array in storage memory). In my example, deleting an array of 1000 addresses by calling delete cost 5060808 gas; deleting the same array by manual assignment cost 5270025 gas.

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.