[Ethereum] Does it cost more gas to call another contract’s functions in solidity

contract-designcontract-developmentgassolidity

I would like to break my code up into multiple contracts, but I'm afraid of this increasing the gas fees. Does an external function call cost more gas than an internal call to a function within the same contract? If so, is it a flat fee for each call or would the size of the arguments being passed factor into it?

Best Answer

A little.

Here's a very idiomatic set of contracts with a set of functions that take different paths to set and get the same value. No effort to optimize for gas. delegateCall can do it cheaper.

You can see the difference in transaction cost, which has to do with packing and unpacking requests. You can see it's (roughly) 2,000 gas extra to set the value with an invocation from the "Module" to the "StandAlone" contract that accomplishes the same thing if called directly.

Two things are worth mentioning.

The proportion of overhead to work is outsized because the contracts aren't doing any heavy lifting themselves. It's basically flat-rate overhead.

The setters are the important comparison. Although gas cost is computed for read-only operations they are essentially free, provided you don't exceed the block gasLimit (the budget).

pragma solidity 0.4.19; 

contract StandAlone {
    uint public x = 1;

    function get() public view returns(uint) {
        return x;
    }

    function set(uint _x) public returns(bool success) {
        x = _x;
        return true;
    }

    function getLongWay() public view returns(uint) {
        return get();
    }
}

contract Module {

    StandAlone s;

    function Module(address SAAddress) public {
        s = StandAlone(SAAddress);
    }

    function get() public view returns(uint) {
        return s.get();
    }

    function set(uint  _x) public returns(bool success) {
        return s.set(_x);
    }
}

Hope it helps.

Related Topic