0
0
Blockchain / Solidityprogramming~7 mins

Storage vs memory vs calldata in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

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.

When you want to save data permanently on the blockchain.
When you need temporary data during a function call.
When you want to pass data to a function without changing it.
Syntax
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.

Examples
This declares a storage array that keeps data permanently.
Blockchain / Solidity
uint[] storage myStorageArray; // Permanent data stored on blockchain
This creates a temporary array that exists only during the function call.
Blockchain / Solidity
function tempData() public {
    uint[] memory tempArray = new uint[](5); // Temporary data
}
This function takes input data that cannot be changed and is cheaper to access.
Blockchain / Solidity
function readOnly(uint[] calldata input) external {
    // input is read-only and cheaper to use
}
Sample Program

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.

Blockchain / Solidity
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;
    }
}
OutputSuccess
Important Notes

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.

Summary

Storage keeps data permanently on the blockchain.

Memory is temporary and used inside functions.

Calldata is read-only input data, cheaper than memory.