Skip to main content

Avoid Misuse Of Public Functions

Description

This code optimization involves avoiding the possible misuse of public functions in Solidity smart contracts. When array arguments are passed to public functions, they are immediately copied to memory, which can be more expensive than reading from calldata. External functions, on the other hand, can read directly from calldata, which can be cheaper and more efficient. Public functions need to write the arguments to memory because they may be called internally, and internal calls are passed internally by pointers to memory. Therefore, the function expects its arguments to be located in memory when the compiler generates the code for an internal function.

Example Code

function publicFunction(uint256[] memory data) public {
// Code block
}

Recommendation

To optimize the code and reduce gas consumption, consider declaring external functions instead of public functions if the function is only expected to be called externally. External functions can read directly from calldata and do not need to copy the arguments to memory, which can save gas and make the code more efficient. Public functions should only be used when the function is expected to be called both internally and externally. The developers should review their Solidity smart contracts to identify and apply this code optimization.