🧩 EVM Components: Stack, Memory & Storage
Learn the three data structures that make smart contracts work
Your Progress
0 / 5 completed←
Previous
How EVM Works
🧩 EVM Components
EVM has four main data locations: Stack (fast temporary), Memory (slow temporary), Storage (permanent, expensive), and Code (immutable). Each serves a specific purpose!
🎮 Interactive: Explore EVM Components
Click each component to learn its characteristics and cost
📚
Stack (256 bits × 1024 slots)
Working memory for operations (LIFO)
Characteristics:
- • Last In, First Out (LIFO) data structure
- • Maximum 1024 items, each 256 bits (32 bytes)
- • Used for opcodes operands and results
- • Cleared after execution completes
Operations:
PUSH (add to top)POP (remove from top)DUP (duplicate)SWAP (reorder)
⛽ Gas Cost:
Very cheap: 3 gas per operation
📝 Example:
PUSH1 5 → Stack: [5] PUSH1 3 → Stack: [5, 3] ADD → Stack: [8]
⚖️ When to Use Each Component
| Use Case | Best Component | Why? |
|---|---|---|
| Math operations (a + b) | Stack | Fast, cheap, perfect for simple ops |
| Function parameters | Memory | Temporary data, doesn't need persistence |
| User balances | Storage | Must persist across transactions |
| Loop counters | Stack | Very cheap for temporary values |
| Array processing | Memory | Can hold large data temporarily |
| Contract logic | Code | Instructions stored immutably |
💡 Cost Comparison Example
✅ Efficient Code
Using stack for temporary values:
uint a = 5;
uint b = 3;
uint sum = a + b;
// Stack only
Gas: ~10
❌ Inefficient Code
Storing in state unnecessarily:
tempSum = a + b;
// SSTORE operation
// Permanent storage!
Gas: ~20,000+
🔒 Security Considerations
⚠️
Storage Collision
Upgradeable contracts can overwrite storage. Use proper slot management (EIP-1967).
⚠️
Memory Expansion
Large memory usage = quadratic gas cost. Can cause out-of-gas errors.
⚠️
Stack Depth
Max 1024 items. Deep recursion can hit limit. Use loops or tail-call optimization.
📊 Memory Layout Example
// Solidity automatically manages memory
function process(uint[] memory data) public {...
// data stored in memory (temporary)
// 0x00-0x3f: scratch space
// 0x40-0x5f: free memory pointer
// 0x60+: your data starts here
}
🎯 Quick Reference
Stack
• Size: 256 bits × 1024 max
• Lifespan: Transaction only
• Cost: ~3 gas
• Use: Quick operations
Memory
• Size: Dynamic (quadratic cost)
• Lifespan: Transaction only
• Cost: ~3-100s gas
• Use: Arrays, strings
Storage
• Size: 2^256 slots × 32 bytes
• Lifespan: Forever
• Cost: ~20,000 gas write
• Use: State variables
Code
• Size: Contract bytecode
• Lifespan: Forever
• Cost: Read is cheap
• Use: Instructions