0Pricing
Web3 & DApp Development Fundamentals · Lesson

Storage Optimization

Packing and slots.

Storage Slots Basics

Contract storage is a giant array of 32-byte slots, indexed from slot 0. State variables are assigned to slots in declaration order.

Every slot you write costs gas, so the fewer slots your data occupies, the cheaper your contract is to use. Understanding the slot layout is the foundation of storage optimization.

contract Layout {
    uint256 a; // slot 0
    uint256 b; // slot 1
    uint256 c; // slot 2
}

Variable Packing

The Solidity compiler packs multiple small variables into a single 32-byte slot when they fit consecutively.

A uint128 uses 16 bytes, so two of them share one slot. A bool uses 1 byte and a uint8 uses 1 byte. Packing reduces both deployment and runtime storage costs.

contract Packed {
    uint128 a; // slot 0 (bytes 0-15)
    uint128 b; // slot 0 (bytes 16-31)
    uint256 c; // slot 1
}

All lessons in this course

  1. Gas Cost Model
  2. Storage Optimization
  3. Loop and Calldata Tricks
  4. Measuring Gas
← Back to Web3 & DApp Development Fundamentals