3

I need help understanding why the first push to a dynamic array is more gas consuming.

For example, executing the push endpoint in the following code:

pragma solidity >0.7.0 <0.8.0;

contract  PushTest{

    uint[] array;
    
    function push ( uint amount) external {
        
        array.push(amount);
    }
}

The first push consumes 41129 gas, while the second one only consumes 26129. I tried to debug the execution with Remix but apparently the same EVM instructions are being executed for the first and following pushes.

2

The first push consumes 41129 gas

That'll be 21,000 gas for the transaction base fee, and 20,000 gas for using the storage associated with the array for the first time. (Plus 129 gas - unsure about this, but probably unimportant.)

while the second one only consumes 26129

That'll be 21,000 gas for the transaction base fee, and 5,000 gas for updating the storage associated with the array. (Plus 129 gas again.)

Main point: Setting a storage value from 0 -> non-zero incurs a 20,000 gas fee. Updating a storage value incurs a 5,000 gas fee.

References:

See Where does the number 21000 come from for the base gas consumption in Ethereum?.

Yellow Paper, Appendix G:

Gsset 20000 Paid for an SSTORE operation when the storage value is set to non-zero from zero.
Gsreset 5000 Paid for an SSTORE operation when the storage value’s zeroness remains unchanged or
is set to zero

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.