Mappings & Arrays
Mappings are hash tables (O(1) lookup, no iteration, no length). Arrays are ordered lists (O(n) iteration, length tracking). Knowing when to use which is the first real architecture decision a Solidity dev makes.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A common pattern: Accessing data efficiently. Mappings are cheap to write/read but can't be looped. Arrays can be looped but get expensive as they grow.
Core Concepts
Mapping
Virtual hash table. All keys exist and map to default value (0). Cannot be iterated.
Array
Contiguous (usually) list of items. Can be dynamic (push/pop) or fixed size.
Sparse
Mappings are sparse; they don't occupy space for empty keys.
Mental Model
The Magic Locker vs. The Shelf
**Mapping**: A locker room with infinite lockers. You can only open a locker if you have the key. You can't say 'show me all lockers with stuff in them' without checking every single one of the 2^256 lockers. **Array**: A shelf of books. You can walk down the line (iterate) and count them, but finding a specific book takes time if you don't know its index.
Under the Hood
Mappings calculate storage slots using `keccak256(key . slot)`. Arrays use `keccak256(slot)` for the data and store the length at the `slot`. Dynamic arrays in memory work differently than storage.
Gas Analysis
Mappings are generally cheaper for random access.
- • Use Mappings for lookups (balances, allowances).
- • Use Arrays only if you simply must iterate or keep order.
- • Avoid unbounded loops over arrays—this is a top security/gas risk.
Security Risks
Array length manipulation and DoS are key risks.
- ! DoS by Block Gas Limit: If an array gets too big, a function iterating it effectively stops working forever.
- ! Deleting an array element leaves a gap; shuffling the last element to the gap is the gas-efficient 'swap-and-pop' trick.
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Click Run to execute the simulation
Then use the step controls to navigate