In blockchain programming, especially in smart contracts, you need to know where data is kept. Storage, memory, and calldata are places to store data, each with different uses and costs.
Storage vs memory vs calldata in Blockchain / Solidity
function example(uint[] memory tempArray, uint[] calldata inputArray) public {
uint[] storage savedArray;
// Use tempArray, inputArray, and savedArray here
}storage means data is saved permanently on the blockchain.
memory means data is temporary and only exists during the function call.
calldata is a special read-only area for function inputs, cheaper than memory.
uint[] storage myStorageArray; // Permanent data stored on blockchain
function tempData() public {
uint[] memory tempArray = new uint[](5); // Temporary data
}function readOnly(uint[] calldata input) external { // input is read-only and cheaper to use }
This smart contract shows how to use storage, memory, and calldata. The saveData function takes input from calldata and saves it permanently in storage. The getTempSum function copies storage data to memory to calculate the sum without changing the stored data.
pragma solidity ^0.8.0; contract DataExample { uint[] public storedData; // storage function saveData(uint[] calldata inputData) external { // Clear old data delete storedData; // Copy inputData from calldata to storage for (uint i = 0; i < inputData.length; i++) { storedData.push(inputData[i]); } } function getTempSum() public view returns (uint) { uint[] memory tempArray = storedData; // copy storage to memory uint sum = 0; for (uint i = 0; i < tempArray.length; i++) { sum += tempArray[i]; } return sum; } }
Storage is expensive because it writes data permanently on the blockchain.
Memory is cheaper and temporary, good for calculations inside functions.
Calldata is the cheapest for input data but is read-only.
Storage keeps data permanently on the blockchain.
Memory is temporary and used inside functions.
Calldata is read-only input data, cheaper than memory.