Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 47 ยท Contract Structure

Storage, Memory and Calldata

Understand Solidity data locations: storage slots and packing, memory, calldata, how costs differ, copy rules and stack depth, with a slot-packing calculator.

When a Solidity function runs, its data can live in several different places, and the choice changes both the behavior and the cost of your code. Reading a variable from the wrong place can cost a hundred times more gas, and assigning a struct can either copy it or point at it depending on where it lives. This is one of the topics that separates "my contract works" from "my contract works at a sane price".

This lesson explains the four places data can live (storage, memory, calldata and the stack), how state variables are laid out in storage slots, what packing does, and the rules for copying between locations.

Where data lives

Storage Permanent. Part of the contract's state. Costly.
Memory Temporary scratch space for one call.
Calldata Read-only input of an external call.
Stack Small slots for local values. Very cheap.
1 / 2

The four locations

Storage is the contract's permanent memory: a huge key-value space of 32-byte slots, numbered from 0, that survives between transactions. Every state variable lives here. It is expensive because every node keeps it forever.

Memory is a byte array that exists only while one external call runs. It is cleared between calls. Using it is cheap, though its cost grows faster than linearly as it expands, so huge memory arrays are expensive too.

Calldata is the read-only region holding the input bytes of an external call (the function selector and arguments). It cannot be modified and is cheaper than copying the arguments into memory, which is why large arrays and strings passed to external functions are best declared calldata.

The stack holds local value types (integers, booleans, addresses) and pointers. The EVM stack is limited to 1,024 slots, and the compiler can only reach the 16 topmost, which leads to the infamous "stack too deep" error when a function has too many locals and parameters. Remedies are splitting the function, grouping values in a struct, or putting some work in a block { ... } so variables go out of scope.

Choosing a data location

Value types (uint, bool, address) never need a location. Reference types (arrays, structs, string, bytes, mappings) do, in these situations:

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Library {
    struct Book { string title; uint16 pages; }
    Book[] public books;                         // state variable: storage, implicit

    function add(Book calldata b) external {     // read-only input, no copy
        books.push(b);                           // calldata -> storage: copies
    }

    function firstTitle() external view returns (string memory) {
        Book storage first = books[0];           // a pointer into storage
        return first.title;                      // copied into memory for returning
    }

    function modified() external view returns (uint16) {
        Book memory copy = books[0];             // storage -> memory: a copy
        copy.pages = 999;                        // changes the copy only
        return copy.pages;
    }

    function rename(uint256 i, string calldata t) external {
        Book storage b = books[i];
        b.title = t;                             // changes the real value
    }
}

The rules to remember:

  • storage local variables are references: writing through them changes the contract's state.
  • Assigning storage to memory (or the other way round) makes a copy.
  • Assigning memory to memory makes a reference: both names see the same data.
  • Calldata cannot be written to, and copying it into storage or memory costs gas for every byte.
  • public and external function parameters can use calldata; if you need to modify the input, use memory.

Strings, Bytes, Arrays and Structs shows these types in detail, and Gas Costs and Optimization applies the rules to real savings.

How state variables use slots

The compiler assigns state variables to slots in the order you declare them, starting at slot 0. Each slot holds 32 bytes. The key rules of the layout:

  • A value smaller than 32 bytes is placed in the current slot if it fits next to the previous values; otherwise a new slot starts. Small values pack together in the order declared.
  • A struct or an array always starts a new slot, and whatever follows it also starts a new slot.
  • A fixed-size array or struct occupies as many consecutive slots as its items need.
  • A mapping takes one slot just to mark its place (the slot itself stays empty). A value is found at the hash of the key and that slot, so entries are scattered across the storage space.
  • A dynamic array stores its length in its slot, and the elements start at the hash of that slot number.

Because a storage read or write moves a whole slot, packing helps: three uint64 values that share a slot are written with one expensive write instead of three. But packing can also cost extra work to mask and shift when the values are read, and it only pays off when the packed values are used together.

SOLIDITY
struct Wasteful {
    uint128 a;     // slot 0
    uint256 b;     // slot 1
    uint128 c;     // slot 2
}
struct Packed {
    uint128 a;     // slot 0, first half
    uint128 c;     // slot 0, second half
    uint256 b;     // slot 1
}

Both structs hold the same data. The second takes two slots instead of three, and just by reordering the fields.

Newer Solidity versions also support transient storage (EIP-1153): values that behave like storage within a transaction but are wiped at its end, with much lower costs. It is mostly used for things like reentrancy locks. Check which compiler version and EVM target your tools support before using it.

A slot calculator you can run

The code below is a stand-in: it reproduces the packing rule for a flat list of value types, but it does not run Solidity and it does not handle mappings, arrays or inheritance. It tells you which slot and byte offset each field would get.

JS Compute storage slots for a struct

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the declared order, each 128-bit value is followed by a 256-bit one, which cannot share its slot, so the two small values waste half a slot each and the struct takes 5 slots. Putting start and count side by side lets them share slot 3, and the struct needs 4. Placing the small fields together is a rule of thumb; the best layout also depends on which values you read together, and a natural order that is easy to read is sometimes worth keeping.

The next stand-in compares the cost of repeated storage reads with caching the value in a local variable, using the rough costs from the slides above. The numbers are simplified (real costs depend on the EVM version and on cold or warm slots), but the shape of the saving is real.

JS Caching a storage read in memory

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the four locations, the rules for packing, the copy and reference rules, and the cold versus warm gap. Stand-in: the layout function handles only flat value types, and the gas meter uses round numbers for illustration, not an exact schedule.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A function parameter of an external function is a large array that the function only reads. Which location is usually cheapest?

    Calldata is read-only and avoids copying the argument into memory, so it is the cheapest choice when the function does not modify the data.
  2. 2. What happens in Book memory copy = books[0]; when books is a storage array?

    Moving a reference type from storage to memory creates an independent copy. To modify the stored value, use a storage reference instead.
  3. 3. A struct is declared as uint128 a; uint256 b; uint128 c;. How many storage slots does it use?

    a takes half of slot 0, but b needs a full slot, so it starts slot 1, and c goes into slot 2. Reordering to a, c, b uses only 2 slots.
  4. 4. What causes the 'stack too deep' compiler error?

    The EVM can only reach the top 16 stack slots, so a function with too many locals cannot address them all. Split the function, group values in a struct or use scopes.

Summary

  • Storage is permanent and expensive, memory is temporary scratch space for a call, calldata is read-only input and the stack holds locals; the stack can only reach 16 slots.
  • State variables take slots in declaration order; values smaller than 32 bytes pack together, while structs, arrays and mappings start new slots.
  • Reordering struct fields can save whole slots, but only pack values that are used together.
  • Storage to memory copies; a storage local is a pointer; memory to memory shares a reference; calldata is never writable.
  • Cache repeated storage reads in a local variable, and use calldata for read-only external parameters.
  • Transient storage is a newer, cheaper per-transaction option, available only on recent compilers and chains.

Next: Inheritance and Overriding.