DEV Community

Cover image for Ethereum-Solidity Quiz Q19: Why is the "external" visibility modifier more gas efficient than "public"?
MihaiHng
MihaiHng

Posted on

Ethereum-Solidity Quiz Q19: Why is the "external" visibility modifier more gas efficient than "public"?

External is more gas efficient than public because of how the compiler generates code differently for each.

For a public function the compiler creates two code paths:

  1. An external entry point — for external callers
  2. An internal function — for internal calls within the contract

This means the function code is duplicated in the bytecode.

For an external function the compiler creates one code path:

  1. An external entry point — for external callers

When an external caller invokes a public function, the compiler has to manage the additional logic to support internal calls, even though the external caller is not using that feature. With external, there's no such additional logic.

When it matters:

  • Deployment gas — external produces smaller bytecode
  • Call gas — external is slightly cheaper to call
  • For functions called frequently — The savings add up

Top comments (0)