0

I have added a new external function to my Solidity smart contract. When checking the gas usage for calls to other already existing external functions, I see the gas usage has increased slightly. Does anyone know why this is? and if the gas increase can be avoided?

1 Answer 1

1

As you have not provided any code, I am writing down a possible reason for this.

It's not because of the external visibility. It's because EVM calls the function on a sorting basis.

Let's say you have 3 functions

function green() public pure returns (string memory) {
    return "green";
      //costs 750 gas
}

function blue() public pure returns (string memory) {
    return "blue";
    //costs 728 gas

}

function red() public pure returns (string memory) {
    return "red";
    //costs 706 gas
}

These functions have their own signatures like this:

"ed18f0a7": "blue()",
"f2f1e132": "green()",
"2930cf24": "red()"

When we call a function, the EVM iterates through this object and matches the function signature that we provided. And that iteration costs gas. This iteration happens in ascending order, for example in the above function signatures, if we try to call any of the three functions, the EVM will first check the red(2930cf24) function, if it doesn't match the one we called then it will check the blue(ed18f0a7) one, and at last the green(f2f1e132) function.

With this logic, you can see the gas difference while calling the above functions. If we remove the blue and red function from the above code, then the green function will cost exactly 706 gas which is equal to what red cost before. Because this time EVM didn't have to iterate through 2 more function signatures.

Let me know if this was clear, also share the code and gas differences in case there's any other reason for this.

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.