Public vs External Functions in Solidity
I have been going through functions in smart contracts code I am creating and decided to make it more explicit s per this best practice .
I noticed that I hesitated whenever I was about to add either the
external visibility mark. This came from a place of uncertainty as to which is better to use when exposing the smart contract functions to outside calls. I came across this excellent answer on StackOverflow.
In a nutshell,
external differs in terms of gas usage. The former use more than the latter when used with large arrays of data. This is due to the fact that Solidity copies arguments to memory on a
public function while
external read from
calldata which a cheaper than memory allocation. I went on to Solidity yellow paper to refresh my memory about call data opcodes.
public functions are called internally and externally. And
internal calls are executed via jumps in the code because array arguments are passed internally by pointers to memory. When the compiler generates the code for an internal function, that function expects its arguments to be located in memory. That is why
public functions are allocated to memory. The optimization that happens with
external is that is does not care for the internal calls.
So if you know you know the function api only allows for
external go for it. It provides performance benefits and you will save on gas.