0
0
Blockchain / Solidityprogramming~30 mins

Storage vs memory vs calldata in Blockchain / Solidity - Hands-On Comparison

Choose your learning style9 modes available
Understanding Storage, Memory, and Calldata in Solidity
📖 Scenario: Imagine you are building a simple smart contract for a blockchain-based voting system. You need to understand how to store and handle data efficiently using storage, memory, and calldata in Solidity.
🎯 Goal: You will create a Solidity contract that stores candidates in storage, uses memory to handle temporary data inside functions, and uses calldata to accept input parameters efficiently.
📋 What You'll Learn
Create a string[] array called candidates stored in storage
Create a function addCandidate that accepts a string parameter using calldata and adds it to candidates
Create a function getCandidateCopy that returns a copy of a candidate's name using memory
Print the candidate's name from getCandidateCopy to demonstrate the output
💡 Why This Matters
🌍 Real World
Smart contracts on blockchains need to manage data efficiently to save gas and work correctly. Understanding where data lives helps developers write better contracts.
💼 Career
Blockchain developers must know how to use <code>storage</code>, <code>memory</code>, and <code>calldata</code> to optimize smart contracts for performance and cost.
Progress0 / 4 steps
1
Create the candidates array in storage
Create a public string[] array called candidates that is stored in storage inside the contract.
Blockchain / Solidity
Need a hint?

Use string[] public candidates; inside the contract to create a storage array.

2
Add a candidate using calldata parameter
Create a public function called addCandidate that takes a string calldata parameter named name and adds it to the candidates array.
Blockchain / Solidity
Need a hint?

Use string calldata name to accept the input efficiently and candidates.push(name); to add it.

3
Return a candidate's name using memory
Create a public view function called getCandidateCopy that takes a uint parameter index and returns a string memory copy of the candidate's name at that index.
Blockchain / Solidity
Need a hint?

Use string memory as the return type to return a copy of the candidate's name.

4
Print the candidate's name from getCandidateCopy
Add a public function called printCandidate that takes a uint parameter index, calls getCandidateCopy with that index, and returns the candidate's name as a string.
Blockchain / Solidity
Need a hint?

Call getCandidateCopy inside printCandidate and return the result.