3

Is using a public function access modifier more gas efficient than using a external function access modifier?

I've been running a few tests with the contact below and have gotten varying results. It also appears to differ based on the order of which I call the inc functions.

Here is the contract I'm testing this with, I've been using Remix IDE to run and have gotten varying results:

contract Storage {
    uint256 number;

    function incP(uint256 i) public {
        number = number + i;
    }

    function incE(uint256 i) external {
        number = number + i;
    }
}

Edit:

Using the code below and running it via Remix.
calling the public function costs: execution cost   2415 gas
calling the external function costs: execution cost 2437 gas

Updated code block:

pragma solidity >=0.8.2 <0.9.0;

contract Storage {
    uint256 number = 5;

    function incP() public view returns(uint256) {
        return number;
    }

    function incE() external view returns(uint256) {
        return number;
    }
}

So given this there is clearly a difference between using public or external function modifier. Does anyone know why?

3 Answers 3

3

Using external functions instead of public does not affect gas.

Up until solidity 0.6.9, only external functions allowed calldata arguments.

Public functions forced the use of the more expensive memory arguments. This means that external functions were more gas efficient than public ones.

From 0.6.9 onwards all functions can use memory and calldata. This means there is now no gas difference.

1
  • It sounds like the takeaway from this is to prefer calldata over memory, for gas efficiency
    – sayandcode
    Commented Jan 8 at 3:51
1

Let's see, you should create 2 contracts StorageP and StorageE.

contract StorageP {
    uint256 public number;

    function inc(uint256 i) public {
      number = number + i;
    }
}

contract StorageE {
    uint256 public number;

    function inc(uint256 i) external {
      number = number + i;
    }
}

Keep in mind: The first storage slot call is more expensive than the next calls.

1

Tangential to the other answers that say external costs the same gas as public: Function order matters, due to some low-level stuff that concerns variable storage access. (The later a function is defined, the more gas it costs (very slightly)). If you want to find out the gas cost of a function use gasleft:

function abc() public view returns (uint gas) {
    gas = gasleft();
    // do stuff
    gas -= gasleft();
    return gas; // this line can be omitted as solidity will auto-return named return variables.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.