
Summary: Data placement in the Ethereum Virtual Machine directly controls persistence, pointer semantics, and gas costs. Solidity exposes three locations for reference types (
array,struct,string,bytes):storage,memory, andcalldata. Mistaking a storage reference pointer for an in-memory copy causes unexpected state mutations or unneeded gas burn. In addition, understanding howkeccak256calculates mapping storage slots explains why mappings cannot be iterated, why they lack a.lengthproperty, and how EVM storage avoids collisions across its slot address space.
1. Three EVM Data Domains
Architectural comparison: evaluating lifecycle, write permissions, and gas expenditure across EVM data tiers.
Every smart contract execution operates across three distinct storage domains:
+----------------------------------------------------------------------------------------------------+
| EVM DATA TIERS |
| |
| [ CALLDATA ] |
| * Scope: Read-only transaction input buffer |
| * Lifetime: Disappears when the call frame ends |
| * Mutability: Strictly Read-Only |
| * Gas Cost: Zero-copy in-place slicing; cheapest access |
| |
| [ MEMORY ] |
| * Scope: Linear byte-array scratchpad allocated during execution |
| * Lifetime: Cleared at function completion |
| * Mutability: Read / Write |
| * Gas Cost: Low linear cost + quadratic memory expansion penalty beyond 724 bytes |
| |
| [ STORAGE ] |
| * Scope: Contract state tree written to the blockchain consensus state |
| * Lifetime: Permanent across all blocks |
| * Mutability: Read / Write |
| * Gas Cost: SSTORE = 2,900 to 20,000 gas; SLOAD = 100 to 2,100 gas |
+----------------------------------------------------------------------------------------------------+
1.1 Comparison Table
| Property | storage |
memory |
calldata |
|---|---|---|---|
| Physical Location | World state Merkle Patricia Trie | Local VM RAM scratchpad | Bytecode transaction payload slice |
| Persistence | Permanent across blocks | Cleared on function exit | Cleared on function exit |
| Read Permission | Yes (SLOAD) |
Yes (MLOAD) |
Yes (CALLDATALOAD) |
| Write Permission | Yes (SSTORE) |
Yes (MSTORE) |
No (Read-only) |
| Assignment Semantics | Reference pointer or copy depending on target | Local copy | Reference pointer to calldata buffer |
| Primary Use | Contract state, user account balances | Temporary computation, local dynamic arrays | External function arguments, batch payloads |
2. Storage Pointers vs. Memory Copies
In Solidity, assigning reference types behaves differently depending on the source and target locations:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract DataLocationSemantics {
struct UserRecord {
uint256 id;
uint256 score;
}
UserRecord public primaryUser = UserRecord(1, 100);
// Storage pointer: points directly to storage slot allocated by primaryUser
function updateWithStoragePointer(uint256 newScore) external {
UserRecord storage userRef = primaryUser;
userRef.score = newScore; // Updates storage slot 1 directly. State changes permanently.
}
// Memory copy: copies data from storage into temporary memory
function updateWithMemoryCopy(uint256 newScore) external view returns (uint256) {
UserRecord memory userCopy = primaryUser;
userCopy.score = newScore; // Modifies the local memory copy only. primaryUser remains untouched.
return userCopy.score;
}
}
Four Assignment Rules:
storagetostorage(local variable): Creates a reference pointer. Changes to the pointer mutate contract state directly.storagetomemory: Creates an independent copy. Mutating the memory variable leaves on-chain storage untouched.memorytostorage: Copies all fields from memory into persistent storage slots, executingSSTOREinstructions.memorytomemory: Creates an in-memory reference pointer. Modifying one updates both references within that call frame.
3. Calldata Zero-Copy Savings
When an external function accepts dynamic arguments (string, bytes, or uint256[]), specifying calldata instead of memory cuts execution gas.
From the open-source repository imminer668/Solidity-Guide (foundry_projects/02_basics/07_Data_Location/src/07_DataLocation.sol):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract DataLocation {
uint256[] public arr;
constructor() {
arr.push(10);
arr.push(20);
arr.push(30);
}
// Calldata parameter: Zero-copy slicing directly from transaction input
function sumCalldata(uint256[] calldata _arr) external pure returns (uint256 total) {
total = 0;
for (uint256 i = 0; i < _arr.length; i++) {
total += _arr[i]; // Direct CALLDATALOAD without memory copying
}
}
// Memory parameter: Allocates memory and copies all elements
function doubleMemory(uint256[] memory _arr) external pure returns (uint256[] memory result) {
result = new uint256[](_arr.length);
for (uint256 i = 0; i < _arr.length; i++) {
result[i] = _arr[i] * 2;
}
}
}
When a function takes uint256[] memory _arr, the EVM loops through calldata bytes and performs MSTORE into memory. For large arrays, this adds memory allocation and expansion costs. With calldata, the EVM reads items directly from the transaction buffer via CALLDATALOAD.
4. Arrays and Unbounded Iteration Risks
Dynamic storage arrays store their length at slot p, with elements positioned starting at:
Iterating over unbounded storage arrays is an anti-pattern:
// Risky pattern
address[] public allInvestors;
function distributeDividends() external {
// If allInvestors grows large, gas exceeds the 30,000,000 block gas limit,
// causing the transaction to revert permanently.
for (uint256 i = 0; i < allInvestors.length; i++) {
payable(allInvestors[i]).transfer(1 ether);
}
}
In production, use pull-based withdrawals where each recipient claims their own balance, or paginate batch jobs with bounded cursors.
5. Mappings and Sparse Hash Slots
Mappings serve as the foundational ledger in ERC-20 balances, ERC-721 ownership, and access lists.
From foundry_projects/02_basics/09_Mapping/src/09_Mapping.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract MappingDemo {
mapping(address => uint256) public balances;
function deposit() external payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) external {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
(bool success,) = payable(msg.sender).call{value: amount}("");
require(success, "Transfer failed");
}
function getBalance(address _addr) external view returns (uint256) {
return balances[_addr];
}
}
5.1 How Mappings Work Under the Hood
Unlike dictionary structures in higher-level languages, a Solidity mapping has no bucket arrays, keeps no key list, and maintains no count.
The EVM storage space spans 32-byte slots. When a mapping is declared at slot position p:
mapping(address => uint256) public balances; // slot p = 0
Slot 0 itself contains nothing. When accessing balances[user], the slot is calculated by hashing the key and the slot index:
Because the address space is , key hash collisions are statistically negligible.
5.2 Structural Consequences:
- No
.length: Mappings lack a counter unless maintained in a separate state variable. - Cannot Enumerate Keys: Querying all holders on-chain requires an auxiliary array (
address[] public accounts). - Default Zero Values: Looking up an unwritten key simply reads an unallocated slot, returning zero.
- Deletion:
delete balances[user]executesSSTORE(slot, 0). It resets the 32-byte word to zero.
6. Testing Data Locations in Foundry
In foundry_projects/02_basics/07_Data_Location/test/07_DataLocation.t.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {DataLocation} from "../src/07_DataLocation.sol";
contract DataLocationTest is Test {
DataLocation public dl;
function setUp() public {
dl = new DataLocation();
}
function testSumCalldata() public view {
uint256[] memory input = new uint256[](3);
input[0] = 10;
input[1] = 20;
input[2] = 30;
uint256 total = dl.sumCalldata(input);
assertEq(total, 60);
}
function testDoubleMemoryDoesNotAlterSource() public view {
uint256[] memory input = new uint256[](2);
input[0] = 5;
input[1] = 15;
uint256[] memory result = dl.doubleMemory(input);
assertEq(result[0], 10);
assertEq(result[1], 30);
assertEq(input[0], 5);
}
}
Run with forge test -vv.
7. Production Context
In production Web3 architectures: – NOVA Membership (中文版): Replaces gas-heavy on-chain loops with sparse mappings, using off-chain indexers to build member directories and leaderboards. – Agent Wallet Guard (中文版): Uses hashed keys combining keccak256(account, epoch, agentId, policyId, dayBucket) to manage independent daily budget counters without cron cleanup jobs. – Aurum RWA (中文版): Uses calldata parameter scoping in compliance modules to verify investor eligibility without extra memory copies.
Review full systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/02_basics/07_Data_Location):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/02_basics/07_Data_Location && forge test -vvv
Expected local verification output:
[PASS] test_StorageReferenceMutatesState() (gas: 31204)
[PASS] test_MemoryCopyLeavesStateUnchanged() (gas: 18450)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
How does the EVM calculate the storage slot of a mapping(address => uint256) entry?
A mapping declared at storage slot p stores nothing at slot p itself. Instead, the value for key k is stored at keccak256(abi.encode(k, p))—concatenating the left-padded 32-byte key with the 32-byte slot index.
Why can’t Solidity return all keys of a mapping?
Because mapping slots are derived via one-way keccak256 hashing over the entire keyspace without storing a key list on-chain. If enumeration is required, pair the mapping with an index array or use OpenZeppelin’s EnumerableMap.
What happens when you assign a storage struct to a memory variable?
The EVM executes a deep copy (SLOAD -> MSTORE) of every struct field into transient memory. Mutating fields on that memory struct will never update persistent contract storage unless explicitly written back.
Series & Related Engineering Guides
- Previous Lesson (S02): Solidity Value Types, Function Visibility, and Gas-Efficient Custom Errors
- Next Lesson (S04): Solidity Architecture Essentials: Interfaces, Access Modifiers, and Indexed Event Design
- Companion Security & Architecture Deep-Dive (T04): Upgradeable Smart Contract Pitfalls: Preventing Storage Collisions, UUPS Locks, and Uninitialized Proxies
- Production Engineering Case Study: Validate Stablecoin Checkout Amounts on the Server
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/02_basics/07_Data_Location) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering