This tutorial series focuses on gas optimization techniques for smart contracts, aiming to help developers effectively save gas fees when developing smart contracts on EVM-compatible chains.
Memory vs Calldata
-
memory
: Typically used for function parameters and temporary variables within functions. Stored in memory and not persistent on the blockchain. -
calldata
: Similar to memory, stored in memory and not persistent on the blockchain. The key difference is that calldata variables are immutable and commonly used for function parameters.
Learn more: Data location and assignment behavior
Below, we demonstrate how to write data using both calldata
and memory
contract CalldataAndMemory {
struct Confi {
uint16 age;
string name;
string wish;
}
Confi John;
Confi Jane;
// using calldata: 67905 gas
function writeToJohn(Confi calldata JohnData) external {
John = JohnData;
}
// using memory: 68456 gas
function writeToJane(Confi memory JaneData) external {
Jane = JaneData;
}
}
Recommendations for gas optimization:
In practical situations, if it’s possible to use calldata, it is recommended to use calldata
instead of memory
.