โ๏ธGas Saving Technique 37: Switching from Public to External Functions for Savings
Introduction: Solidity offers various function visibility specifiers, including public
and external
. While both can be accessed from outside the contract, switching from public
to external
in certain scenarios can save gas and lead to more efficient smart contracts.
Concept:
Function Visibility:
public
: These functions can be called both externally and internally (from within the contract or derived contracts). When used externally, arguments are passed in calldata, and when used internally, arguments are passed in memory.external
: These functions can only be called from other contracts and transactions. Arguments are always in calldata, which is a read-only, low-level data area.
Gas Efficiency: Calling an
external
function is typically more gas-efficient than apublic
function when called externally becauseexternal
functions can skip one step of copying argument data (from calldata to memory).
Examples & Recommendations:
Problem: Having a public
function that's never called from within the contract. Solution: Change its visibility to external
.
Non-Optimized Approach:
Optimized Approach:
Step-by-Step Guide for Switching to External Functions:
Review: Identify
public
functions in your contract that are never called internally.Change Visibility: For functions identified in step 1, change their visibility from
public
toexternal
.Test: After making the change, ensure that the contract's functionality remains consistent. The function should still be callable from external contracts and transactions.
Benefits:
Gas Savings:
external
functions use less gas thanpublic
functions when called externally because of reduced data copying.Code Clarity: Using
external
visibility clearly indicates that a function is not meant to be called internally, leading to improved code semantics and readability.
Considerations:
Internal Calls: If a function is or will be used both externally and internally, it should remain
public
.Proxy Contracts: If using proxy patterns, ensure the visibility of functions aligns with intended usage across different contract versions.
Statement Verification: Is the statement "External call cost is less expensive than of public functions" true?
Yes, the statement is generally true when referring to calls made externally to the contract. As mentioned, external
functions can leverage calldata directly, avoiding the need for data to be copied to memory, which incurs additional gas.
Conclusion: Switching appropriate public
functions to external
can lead to gas savings and clearer code. However, always consider the function's intended use case before making such changes to ensure functionality remains consistent.
Last updated