0

Why gas prices vary according to state visibility(public/external/private/internal) to Function?

2 Answers 2

2

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

1

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:

https://medium.com/coinmonks/deciphering-visibility-specifiers-in-solidity-from-basics-to-optimizations-to-security-b0ea0a03aa1f

`external` vs `public` best practices

Private vs internal cheaper

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.