0
0
Blockchain / Solidityprogramming~3 mins

Storage vs memory vs calldata in Blockchain / Solidity - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how choosing the right data location can save you big on blockchain costs and headaches!

The Scenario

Imagine you are writing a smart contract that needs to handle user data. You try to store all data directly on the blockchain every time a function runs, or you pass large data around without thinking about where it lives. This quickly becomes expensive and slow.

The Problem

Storing everything permanently on the blockchain costs a lot of gas and slows down your contract. Using temporary data incorrectly can cause bugs or waste resources. Without knowing where data lives--storage, memory, or calldata--you risk making your contract inefficient and costly.

The Solution

Understanding the difference between storage, memory, and calldata helps you manage data smartly. Storage keeps data permanently on the blockchain, memory is temporary during function execution, and calldata is read-only input data. Using each correctly saves gas, improves speed, and prevents errors.

Before vs After
Before
string storage storageData;

function saveData(string memory data) public {
  storageData = data; // always stores permanently
}
After
function processData(string calldata data) public {
  string memory temp = data; // temporary and cheaper
  // process temp without storing permanently
}
What It Enables

It enables writing efficient, cost-effective smart contracts that handle data correctly and save precious blockchain resources.

Real Life Example

When a user sends a transaction with input data, using calldata lets your contract read it without extra cost. If you need to keep data forever, storage is the right place. For temporary calculations, memory is perfect.

Key Takeaways

Storage is permanent and costly.

Memory is temporary and cheaper.

Calldata is read-only input data, cheapest to use.