1

I would like to make sure that the gas cost of adding an item to a (storage) array is constant, i.e., not dependent on the length of the array.

To my understanding, the relevant EVM operation is SSTORE, which according to this spreadsheet (taken from the yellow paper), has indeed a "more or less constant" gas cost.

In addition to that, I also found this answer to support it, stating:

As far as I know, adding an item to an array/mapping will cost the same gas regardless of how many items that array/mapping already is storing.

Due to the "as far as I know" part, I also executed some testing against a "real" EVM (using Truffle and Ganache).

Here is my on-chain code:

pragma solidity ^0.4.24;

contract MyContract {
    uint256[] public array;
    function justPush(uint256 value) external {
        array.push(value);
    }
}

Here is my off-chain code:

contract("test", function() {
    it("pushing an 'all-0s' value", async function() {await justPush(1);});
    it("pushing an 'all-1s' value", async function() {await justPush(2);});

    async function justPush(n) {
        let myContract = await artifacts.require("MyContract.sol").new();
        let value = web3.toBigNumber(n).pow(256).minus(1);
        for (let i = 0; i < 1000; i++) {
            let gas = await myContract.justPush.estimateGas(value);
            await myContract.justPush(value);
            console.log(gas);
        }
    }
});

And here is my observation:

  • Pushing an "all-0s" value costs 46951 units for the first insertion and 31951 units for every other insertion
  • Pushing an "all-1s" value costs 63999 units for the first insertion and 48999 units for every other insertion

As I started off with - I would like to make sure that the gas cost of this operation is indeed constant, even though the operation of adding an element to an array which not implemented as a linked list has a theoretical time complexity of O(n).

Also, am I right in guessing that the difference between the first insertion and every other insertion is due to the fact that the length of the array is changed from 0 to 1?

Thank you!

Your Answer

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

Browse other questions tagged or ask your own question.