0

Since dynamically increasing in-memory arrays is not allowed in Solidity, I thought about creating a helper method like the below to create a new array with one more element every time I wanted to increase the size. What is the disadvantage of doing this since everything is done in memory? Thank you.

contract ArrayTest {
    function test() internal pure returns (address[] memory) {
        address[] memory a = new address[](1);
        a[0] = address(0);
        a = push(a, address(1));
        a = push(a, address(2));
        a = push(a, address(3));
        a = push(a, address(4));
        a = push(a, address(5));
        return a;
    }

    function push(address[] memory a, address addressToPush)
        internal
        pure
        returns (address[] memory)
    {
        // create the new array with one element larger than the passed in array
        address[] memory b = new address[](a.length + 1);
        // copy the old array into the new array
        for (uint256 i = 0; i < a.length; i++) {
            b[i] = a[i];
        }
        // add the new element to the end
        b[b.length - 1] = addressToPush;
        // return the new array
        return b;
    }
}

2 Answers 2

1

You allocate new memory each time when you add a new item. At some point allocating memory goes from linear costs to quadratic costs, therefore becoming quite expensive.

1

In short - it's more expensive. How much depends on how often your have to do it. Expanding a small array like this once is no big deal but if you need to do it repeatedly you should look for alternatives.

Here's how it specifically affects gas usage:

  • If you could just increase the size in place, it would be O(1) complexity in terms of computation because you would only need to write the newly added element. In your method you rewrite every item so it's O(n) instead.
  • The way you do it in your example is especially inefficient in case you need to add more than one item. Adding m items will cost you O(m * n) that way. You could do it in O(m + n) by defining a function that can add m elements in one go.
  • Solidity has no memory management/garbage collection so anything you allocate stays there until your call terminates. This matters because there's an extra cost associated with writing to yet unused areas of memory. See what is expansion cost?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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