Gas Cost – Do Intermediate Memory Variables Cost Gas in Solidity?

gas-estimateoptimizationsolcsolidity

Example without an intermediate variable:

uint startTime = 9;
uint allowedTime = 7;

require(now > startTime + allowedTime);

Example with an intermediate variable:

uint startTime = 9;
uint allowedTime = 7;

uint deadline = startTime + allowedTime;

require(now > deadline);

Obviously those two blocks above are functionally equivalent, but the latter one introduces an intermediate variable to increase readability. I would expect the intermediate variable to cancelled out when source code gets compiled, so those two example should produce the same bytecode. If this is the case there should be no extra gas cost for usage of an intermediate variable.

Why bother? Those examples above are simple but in real situations sometimes intermediate variables are extremely useful to reduce congnitive load of reader (readible code -> bug-free code -> secure contract). So I wan't to use it if it's free gas-wise.

Now comes the question: Do intermediate variables get cancelled out by Solidity compiler and cost no extra gas? Or Solidity compiler is not that smart yet?

Best Answer

Here is more information about storing data in solidity https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#storage-memory-and-the-stack

Those variables, which you defined, will be stored in stack(if there is a space and you keep them in one function). in case if compile will optimize it properly it will be for free, if not, each variable will cost you PUST and POP operations (3+2 gas)

UPDATE

Optimized bytecode costs same amount of gas for both versions. Checked on pragma solidity 0.4.24

Ropsten test (Remix)

pragma solidity ^0.4.24;
contract A {
    uint t;

    function run() public returns(uint){
        uint startTime = 9;
        uint allowedTime = 7;

        uint v = startTime + allowedTime; // second test without v
        t = now + v;
        return t;
    }
}

Results:

with v
  deploy 95237 gas
  func 41470 gas

without v
  deploy 95237 gas
  func 41470 gas
Related Topic