In Solidity, there are 3 locations for data to be stored. Storage is reserved for data that is stored on the blockchain permanently, Memory is used for temporary computations, and Calldata is reserved for function arguments that don’t require any manipulation. Here is an example of Storage, Memory, and Calldata in Solidity:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
contract dataLocations{
uint public age = 30;
function storageExample() public view returns(uint){
return age;
}
struct hand{
bool hand;
bool index;
bool middle;
bool ring;
bool pinky;
}
function memoryExample(bool a, bool b, bool c, bool d, bool e) public pure returns(hand memory){
hand memory myHand = hand(a,b,c,d,e);
return myHand;
}
function calldataExample(string calldata _name) public pure returns (string memory){
return string.concat(_name," is amazing.");
}
}
Storage is used for permanent data on the blockchain, and using storage as a data location will always alter the blockchain.
Memory is used for temporary data on the blockchain, and the most frequent use case is for calculations or processes inside a function.
Calldata is a special type of memory that is also temporary, but more gas efficient than memory. Calldata can only be used on function arguments. The main difference between calldata and memory, is that memory will make a copy of the data being referenced to perform computations, while calldata will not.
Calldata is immutable, meaning it can’t be modified, only viewed.