I know that external
is cheaper than public
due to how arguments are parsed. Is making a function private
or internal
cheaper?
-
have you tried to monitor the gas in a testnet in both scenarios to check which one is cheaper? I am guessing it is the private function as opposed to internal but it is worth trying.– AnonymousCommented Nov 27, 2021 at 17:26
2 Answers
I have just checked with a small example in JavaScript VM environment of Remix using the following contract:
contract test {
function calc(uint256 a, uint256 b) private returns (uint256) {
return a + b;
}
function test(uint256 a, uint256 b) public returns (uint256) {
return calc(a, b);
}
}
Changing the visibility of calc
from private
to internal
does not change the cost of gas when calling test
.
However, I have done a 2nd test by putting the two version of calc
in one contract, i.e. calc1
as private
and calc2
as internal
.
Then the function defined first in the source code shows a slightly lower gas consumption, however, this is not linked to its visibility. If the first function is private
, it's cheaper. And if internal
heads the code, it's vice versa.
So I come to the conclusion that gas cost are the same. This would also be in line with my understanding that the distinction between private
and internal
isn't relevant anymore after the code has been compiled.
https://solidity.readthedocs.io/en/latest/contracts.html?highlight=private
internal: Those functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this. private: Private functions and state variables are only visible for the contract they are defined in and not in derived contracts.
-
2