Control Variable Visibility
for variables
Visibility modifiers restrict who can use values of Solidity variables. Here is a list of modifiers that change these permissions:
public
: anyone can get the value of a variable.external
: only external functions can get the value of a local variable. It is not used on state variables.internal
: only functions in this contract and inherited contracts can get values.private
: access limited to functions from this contract.
public = external + internal
public functions cost more gas than either external or internal. To save gas, restrict to external/internal when possible.
public vs external
public
and 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 is cheaper than memory allocation.
public
functions are called internally and externallyinternal
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 the function you create only allows for external
calls, go for it. It provides performance benefits and you will save on gas.
Immutable v Constant
for constant variables, the value has to be fixed at compile-time, (initial and assign in one line)
for immutable, it can still be assigned at construction time (within constructor)
Last updated