0
0
Blockchain / Solidityprogramming~5 mins

Storage vs memory usage in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Storage and memory are two ways to keep data in blockchain programs. Storage keeps data safe for a long time, while memory is used for quick, temporary data during a task.

When you want to save user information that stays after the program stops.
When you need to handle data only while a function runs and then forget it.
When you want to reduce costs by using less permanent storage.
When you want to quickly access data without saving it permanently.
Syntax
Blockchain / Solidity
// Solidity example
contract Example {
    uint[] storageArray; // stored permanently

    function useMemory() public {
        uint[] memory tempArray = new uint[](5); // temporary memory
    }
}

Storage means data saved on the blockchain permanently.

Memory means temporary data used during function execution only.

Examples
This saves the number 10 permanently in the contract's storage.
Blockchain / Solidity
// Storage example
uint[] storageArray;
storageArray.push(10);
This creates a temporary array that disappears after the function ends.
Blockchain / Solidity
// Memory example
function tempData() public {
    uint[] memory tempArray = new uint[](3);
    tempArray[0] = 1;
}
Sample Program

This contract shows how to add data permanently to storage and how to use temporary memory to calculate a sum.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract StorageVsMemory {
    uint[] public storedData;

    function addToStorage(uint value) public {
        storedData.push(value); // saved permanently
    }

    function processMemory() public pure returns (uint) {
        uint[] memory temp = new uint[](3);
        temp[0] = 5;
        temp[1] = 10;
        temp[2] = 15;
        uint sum = 0;
        for (uint i = 0; i < temp.length; i++) {
            sum += temp[i];
        }
        return sum; // returns 30
    }
}
OutputSuccess
Important Notes

Using storage costs more gas because it saves data permanently on the blockchain.

Memory is cheaper but data is lost after the function finishes.

Choose storage for data you want to keep, memory for temporary calculations.

Summary

Storage keeps data permanently on the blockchain.

Memory holds temporary data during function execution.

Use storage for saving important data, memory for quick, temporary use.