An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
Solidity: external vs. public & memory vs. calldata vs. storage
It is written in many places how these things are. But what not easy to decide when to use which of them, as it needs a deeper understanding to choose.
So I want to note the quick heuristic methods to choose these.
Public vs. External
TL;DR;
So if you know the function you create only allows for external calls, go for it. It provides performance benefits and you will save on gas.
Sometimes, we think it could be any of both, we can go for external as for external functions, the compiler doesn't need to allow internal calls, and so it allows arguments to be read directly from calldata
, saving the copying step. While public can be internal or external call.
Easy read here:
- https://gus-tavo-guim.medium.com/public-vs-external-functions-in-solidity-b46bcf0ba3ac
- https://ethereum.stackexchange.com/a/19391/76945
Memory vs. Calldata vs. Storage
TL;DR;
- use
calldata
when you only need read-only data, avoiding the cost of allocating memory or storage.- use
memory
if you want your argument to be mutable.- use
storage
if your argument will already exist in storage, to prevent copying something into storage over into memory unnecessarily.
Ref:
To research more
I am still not sure why most of the OpenZeppelin libs choose to use memory
over calldata
, although they don't mutate them. For example: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol#L179
Original Link: https://dev.to/turboza/solidity-external-vs-public-memory-vs-calldata-vs-storage-33bg
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To