Why gas prices vary according to state visibility(public/external/private/internal) to Function?
2 Answers
In Ethereum, transactions cost gas and hence ether. The gas consumption of a transaction depends on the opcodes that the EVM has to execute. So it's all about the opcode being used.
More opcode, more gas used (some opcode are really expensive because they are computationally heavy)
For exemple, using visibility external for the functions only accessed externally forces to use calldata as the parameter location and this saves some gas when the function executes.
You also have this great twitter thread about forge inspect @CONTRACT ir-optimized
that will help you visualize what opcode are being used by your code
https://twitter.com/w1nt3r_eth/status/1579486967963693057
Hope this helps
Gas prices vary according to state visibilities mainly due to how the data are manipulated, especially between public and external specifiers. Public visibility generally costs more gas because arguments in public functions are copied to memory
, while functions with external visibility can read arguments directly from calldata
, which costs less gas since using calldata
is cheaper than using memory
. However, the gas cost for internal vs. private specifiers are nearly the same.
See: