1

I'm running a smart contract locally on TestRPC and using MetaMask to interact with it. Repeatedly calling the same function with the same parameters seems to accumulate different gas consumption (including the gas estimate in MetaMask). Is it possible or am I missing something?

3

This is possible, depending on what the contract does. There are three main factors that can make gas consumption vary, even if the function is called with the exact same arguments:

  • Writing a non-zero value to a storage location that contains a 0 costs more than writing to a storage location that already contained a non-zero value. (20000 vs 5000 gas)

    For example:

    uint a = 0; function test() { a++; }

    In this example, the first call to test will cost 15000 more gas than the subsequent calls, because a 0 storage value was changed to a non-zero value.

  • Writing a 0 value to a storage location refunds 15000 gas (if it wasn't already zero)

  • Control flow inside the function you're calling may run differently if it depends on the state of the contract, or if it depends on some external state such as msg.sender or this.balance

Calls to a function that does not write to or read from storage (the contract's state variables) should always consume exactly the same amount of gas, as long as the arguments are the same of course.

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.