Skip to content
Back to Curriculum
INTERNALS

Memory vs Calldata

`memory` is temporary storage that is erased after transaction execution. `calldata` is a non-modifiable, non-persistent area where function arguments are stored. Calldata behaves like memory but is cheaper and read-only.

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

Comparing the cost of Memory copies vs Calldata slicing.

Practical.sol
Loading...

Core Concepts

Memory Expansion

Gas cost grows logically with size, but Quadratically after a threshold. Allocating HUGE memory is very expensive.

Free Memory Pointer

Points to the next free specific byte in memory (0x40).

Mental Model

The Scratchpad vs. The Speech

**Calldata** is the speech someone gave you. It's written in stone (or audio recording); you can listen to it, but you can't change what they said. **Memory** is your scratchpad. You can copy parts of the speech there and edit them, cross them out, or write new things.

Under the Hood

Memory is a byte array. Solidity manages a 'Free Memory Pointer' at address 0x40. When you say `new bytes(100)`, it reads 0x40, reserves 100 bytes, and updates 0x40.

MSTOREMLOADCALLDATALOADCALLDATASIZE

Gas Analysis

Avoid copying if possible.

  • • Always use `calldata` for external function parameters if you don't need to modify them.
  • • Reuse memory arrays instead of creating new ones in a loop.

Security Risks

Memory safety is generally high.

  • ! Allocating dynamic memory based on user input size can lead to Out of Gas Denial of Service.

Common Use Cases

Processing arrays without saving to storage.
String manipulation.
Saving gas on external function calls.

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Interactive Simulation
0 / 0
Loading...
Type Solidity code (v0.8.26) and click Run. Compiler loads on first use (~2MB).

Click Run to execute the simulation

Then use the step controls to navigate