7

Here is a simple Solidity contract:

pragma solidity ^0.4.16;

contract Test {
    uint[] array;

    function testGasEstimation() public {
        array.length = 1;
    }
}

Here is the output of solc --gas Test.sol

======= Test.sol:Test =======
Gas estimation:
construction:
   88 + 44200 = 44288
external:
   testGasEstimation(): infinite

Similarly array.push(1); estimates to infinite gas.

6

There are many cases when the gas estimator reports infinite gas. However, it doesn't necessarily mean that there is an infinite loop in your code or that your code is incorrect but just the estimator is quite restrictive when making decisions about how much gas can be consumed by the code. In particular, any backward jumps or loops in the assembly code will make it report infinite gas.

For the provided code sample array.length = 1; the compiler adds the bytecode that resets all array elements outside the new bound. For example if the array contained 10 elements and then you set its length to 1, the code will iterate over 9 elements and reset the storage slots for them. This operation involves a loop, that's why the estimator reports infinite gas estimation.

array.push() includes setting the new length of the array, so it's estimated to infinity for the same reasons.

You can read more details with links to the estimator code here How to get the cost (in gas) of the non-constant function call?

1

Dynamic array could have infinite length, regardless that you set it to 1.

  • 2
    Does it mean setting the length of potentially infinite array to 1 potentially takes infinite gas? – medvedev1088 Nov 3 '17 at 10:26
  • 2
    Between you an me know, but the compiler can not work that out, because it can not know that you may have a function or call later that changes the value, yes you have a constant, but to the compiler, it interprets it as a variable, and as such could be infinite, this is just be guess from my understanding, don't gp to the bank on this...:D – Cyberience Nov 7 '17 at 2:44

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.