{"eip":3336,"title":"Paged memory allocation for the EVM","description":"Changes the memory model for the EVM to use pagination.","authors":["Nick Johnson (@arachnid)"],"status":"Stagnant","type":"Standards Track","category":"Core","created":"2021-03-06","discussionsTo":"https://ethereum-magicians.org/t/eips-3336-and-3337-improving-the-evms-memory-model/5482","repo":"EIPs","label":"EIP-3336","officialUrl":"https://eips.ethereum.org/EIPS/eip-3336","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3336.md","url":"https://eips.huatuo.xyz/eip-3336/","tldr":{"en":"Proposed switching EVM memory from one linearly-priced array to 1 KiB pages paid for only when touched, so compilers could spread data across the address space without paying for the gaps.","ja":"EVM のメモリを、線形に課金される 1 つの配列から、触れたときだけ支払う 1 KiB ページへ切り替える提案。コンパイラが隙間の分を払わずにアドレス空間全体へデータを配置できるようにする。","ko":"EVM 메모리를 선형으로 가격이 매겨지는 하나의 배열에서, 건드릴 때만 비용을 내는 1 KiB 페이지 방식으로 바꾸자는 제안. 컴파일러가 빈 공간 비용을 내지 않고 데이터를 주소 공간 전체에 흩어 놓을 수 있게 한다.","zh":"提议把 EVM 内存从一个线性计价的数组改为按 1 KiB 分页、仅在访问时付费，这样编译器就可以把数据分散在整个地址空间，而无需为空隙付费。"},"tags":["evm","memory","gas","compilers","core"],"explainers":{"en":{"lang":"en","tldr":"Proposed switching EVM memory from one linearly-priced array to 1 KiB pages paid for only when touched, so compilers could spread data across the address space without paying for the gaps.","tags":["evm","memory","gas","compilers","core"],"related":[3337,2929],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-3336/","markdown":"## What problem does it solve?\n\nEVM memory is a single byte array that starts at address 0. You pay for it up to the **highest** address you have touched, using a cost that grows quadratically:\n\n```\nCmem(a) = 3 * a + floor(a² / 512)      # a = words from 0 to the highest touched word\n```\n\nTouching address 1,000,000 means paying for every word below it, even if you never use them. Compilers therefore pack memory tightly and often copy data around to keep it compact. That wastes gas and rules out familiar layouts such as a separate heap and stack in different regions.\n\nOrdinary computers solve this with virtual memory: a huge address space where only the pages actually used are backed by RAM. EIP-3336 proposes a simple version for the EVM.\n\n## How it works\n\nParameters: `PAGE_BITS = 10` (pages of 1,024 bytes) and `PAGE_BASE_COST = 96`.\n\n- The top 246 bits of an address are the page number; the low 10 bits are the offset within the page.\n- A page is allocated (zero-filled) the first time any byte in it is read or written. Clients are encouraged to store pages in a hash map keyed by page number.\n- Memory cost depends on the **number of allocated pages** `p`, not the highest address:\n\n```\nCmem'(p) = max(96 * (p - 1) + floor(2 * (p - 1)²), 0)\n```\n\n  The first page is free, and the curve is designed to never charge more than the current formula for the same amount of memory.\n- `MLOAD`/`MSTORE` stay at 3 gas when the 32-byte word sits in one page, but cost 6 gas if it straddles two pages, to pay for the extra work of splitting it.\n- Every other memory-touching opcode (`CALLDATACOPY`, `CODECOPY`, `CALL`, `CREATE`, `MSTORE8`, …) allocates any pages it touches and charges the new expansion cost.\n\n## Sample code\n\nComparing old and new memory cost for a sparse access pattern (Python):\n\n```python\nPAGE_BITS, PAGE_BASE_COST = 10, 96\nPAGE_SIZE = 1 \u003c\u003c PAGE_BITS\n\ndef old_cost(highest_byte: int) -\u003e int:\n    a = (highest_byte + 32) // 32          # words from 0 to highest touched word\n    return 3 * a + a * a // 512\n\ndef new_cost(pages: int) -\u003e int:\n    return max(PAGE_BASE_COST * (pages - 1) + 2 * (pages - 1) ** 2, 0)\n\ntouched = [0x0000, 0x10_0000]              # two words, ~1 MiB apart\npages = {addr \u003e\u003e PAGE_BITS for addr in touched}\nprint(old_cost(max(touched)))              # 2,195,587 gas\nprint(new_cost(len(pages)))                # 98 gas\n```\n\n## Things to know\n\n- **Status: Stagnant.** It was never scheduled for a hard fork; EVM memory pricing is still linear-from-zero.\n- It was proposed together with [EIP-3337](/eip-3337/) (frame-pointer memory loads and stores) to improve the EVM's memory model.\n- Programs doing unaligned 32-byte loads/stores across a page boundary would pay slightly more; the authors expected this to affect few contracts.\n- The spec's test cases are listed as TBD.\n"},"ja":{"lang":"ja","tldr":"EVM のメモリを、線形に課金される 1 つの配列から、触れたときだけ支払う 1 KiB ページへ切り替える提案。コンパイラが隙間の分を払わずにアドレス空間全体へデータを配置できるようにする。","tags":["evm","memory","gas","compilers","core"],"related":[3337,2929],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-3336/","markdown":"## 何を解決するのか\n\nEVM のメモリは、アドレス 0 から始まる 1 本のバイト配列です。触れた**最大の**アドレスまでの分を、2 次関数的に増えるコストで支払います。\n\n```\nCmem(a) = 3 * a + floor(a² / 512)      # a = words from 0 to the highest touched word\n```\n\nアドレス 1,000,000 に触れれば、使っていなくてもその下のすべてのワードの分を支払うことになります。そのためコンパイラはメモリを詰めて配置し、コンパクトに保つためにデータをあちこちコピーすることがよくあります。これはガスの無駄であり、ヒープとスタックを別々の領域に置くといった、おなじみのレイアウトも不可能にします。\n\n通常のコンピューターは、仮想メモリでこれを解決します。巨大なアドレス空間のうち、実際に使われるページだけが RAM に裏付けられます。EIP-3336 は、その単純なバージョンを EVM に提案します。\n\n## 仕組み\n\nパラメーターは `PAGE_BITS = 10`（1,024 バイトのページ）と `PAGE_BASE_COST = 96` です。\n\n- アドレスの上位 246 ビットがページ番号、下位 10 ビットがページ内のオフセットです。\n- ページは、その中のいずれかのバイトが初めて読み書きされたときに（ゼロ埋めで）割り当てられます。クライアントは、ページ番号をキーとするハッシュマップにページを保存することが推奨されます。\n- メモリコストは、触れた最大アドレスではなく、**割り当て済みのページ数** `p` に依存します。\n\n```\nCmem'(p) = max(96 * (p - 1) + floor(2 * (p - 1)²), 0)\n```\n\n  最初のページは無料で、同じ量のメモリに対して現行の式より多く課金しないように曲線が設計されています。\n- `MLOAD` / `MSTORE` は、32 バイトのワードが 1 ページ内に収まる場合は 3 ガスのままですが、2 ページにまたがる場合は、分割のための追加作業の分として 6 ガスかかります。\n- メモリに触れるその他のすべての opcode（`CALLDATACOPY`、`CODECOPY`、`CALL`、`CREATE`、`MSTORE8` など）は、触れたページを割り当て、新たな拡張コストを課金します。\n\n## サンプルコード\n\n疎なアクセスパターンに対する、旧コストと新コストの比較（Python）:\n\n```python\nPAGE_BITS, PAGE_BASE_COST = 10, 96\nPAGE_SIZE = 1 \u003c\u003c PAGE_BITS\n\ndef old_cost(highest_byte: int) -\u003e int:\n    a = (highest_byte + 32) // 32          # words from 0 to highest touched word\n    return 3 * a + a * a // 512\n\ndef new_cost(pages: int) -\u003e int:\n    return max(PAGE_BASE_COST * (pages - 1) + 2 * (pages - 1) ** 2, 0)\n\ntouched = [0x0000, 0x10_0000]              # two words, ~1 MiB apart\npages = {addr \u003e\u003e PAGE_BITS for addr in touched}\nprint(old_cost(max(touched)))              # 2,195,587 gas\nprint(new_cost(len(pages)))                # 98 gas\n```\n\n## 知っておくべきこと\n\n- **ステータス: Stagnant（停滞）。** ハードフォークに予定されたことはなく、EVM のメモリ価格は今もゼロからの線形です。\n- EVM のメモリモデルを改善するため、[EIP-3337](/eip-3337/)（フレームポインター方式のメモリロードとストア）とあわせて提案されました。\n- ページ境界をまたぐアラインされていない 32 バイトのロード／ストアを行うプログラムは、わずかに多く支払うことになります。著者は、影響を受けるコントラクトは少ないと見込んでいました。\n- 仕様のテストケースは TBD と記されています。\n"},"ko":{"lang":"ko","tldr":"EVM 메모리를 선형으로 가격이 매겨지는 하나의 배열에서, 건드릴 때만 비용을 내는 1 KiB 페이지 방식으로 바꾸자는 제안. 컴파일러가 빈 공간 비용을 내지 않고 데이터를 주소 공간 전체에 흩어 놓을 수 있게 한다.","tags":["evm","memory","gas","compilers","core"],"related":[3337,2929],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-3336/","markdown":"## 어떤 문제를 해결하나요?\n\nEVM 메모리는 주소 0에서 시작하는 하나의 바이트 배열입니다. 건드린 **가장 높은** 주소까지의 전체에 대해 비용을 내며, 그 비용은 이차식으로 늘어납니다.\n\n```\nCmem(a) = 3 * a + floor(a² / 512)      # a = words from 0 to the highest touched word\n```\n\n주소 1,000,000을 건드리면 그 아래 모든 워드의 비용을 내야 하며, 한 번도 쓰지 않았더라도 마찬가지입니다. 그래서 컴파일러는 메모리를 빽빽하게 배치하고, 간결하게 유지하려고 데이터를 이리저리 복사하는 일이 많습니다. 이는 가스를 낭비하고, 힙과 스택을 서로 다른 영역에 두는 익숙한 레이아웃도 불가능하게 합니다.\n\n일반 컴퓨터는 가상 메모리로 이 문제를 해결합니다. 거대한 주소 공간 중 실제로 쓰이는 페이지만 RAM이 뒷받침합니다. EIP-3336은 그 단순한 버전을 EVM에 제안합니다.\n\n## 어떻게 동작하나요?\n\n파라미터는 `PAGE_BITS = 10`(1,024바이트 페이지)과 `PAGE_BASE_COST = 96`입니다.\n\n- 주소의 상위 246비트가 페이지 번호이고, 하위 10비트는 페이지 내 오프셋입니다.\n- 페이지는 그 안의 어떤 바이트든 처음 읽거나 쓸 때 (0으로 채워져) 할당됩니다. 클라이언트는 페이지 번호를 키로 하는 해시 맵에 페이지를 저장하도록 권장됩니다.\n- 메모리 비용은 가장 높은 주소가 아니라 **할당된 페이지 수** `p`에 따라 정해집니다.\n\n```\nCmem'(p) = max(96 * (p - 1) + floor(2 * (p - 1)²), 0)\n```\n\n  첫 번째 페이지는 무료이며, 같은 양의 메모리에 대해 현재 공식보다 더 많이 부과하지 않도록 곡선이 설계되어 있습니다.\n- `MLOAD`/`MSTORE`는 32바이트 워드가 한 페이지 안에 있으면 3 가스 그대로이지만, 두 페이지에 걸치면 이를 쪼개는 추가 작업 비용으로 6 가스가 듭니다.\n- 메모리를 건드리는 다른 모든 opcode(`CALLDATACOPY`, `CODECOPY`, `CALL`, `CREATE`, `MSTORE8` 등)는 건드린 페이지를 할당하고 새 확장 비용을 부과합니다.\n\n## 샘플 코드\n\n드문드문한 접근 패턴에서 기존 메모리 비용과 새 메모리 비용 비교(Python):\n\n```python\nPAGE_BITS, PAGE_BASE_COST = 10, 96\nPAGE_SIZE = 1 \u003c\u003c PAGE_BITS\n\ndef old_cost(highest_byte: int) -\u003e int:\n    a = (highest_byte + 32) // 32          # words from 0 to highest touched word\n    return 3 * a + a * a // 512\n\ndef new_cost(pages: int) -\u003e int:\n    return max(PAGE_BASE_COST * (pages - 1) + 2 * (pages - 1) ** 2, 0)\n\ntouched = [0x0000, 0x10_0000]              # two words, ~1 MiB apart\npages = {addr \u003e\u003e PAGE_BITS for addr in touched}\nprint(old_cost(max(touched)))              # 2,195,587 gas\nprint(new_cost(len(pages)))                # 98 gas\n```\n\n## 알아둘 점\n\n- **상태: Stagnant(정체).** 하드 포크에 예정된 적이 없으며, EVM 메모리 가격은 여전히 0부터 시작하는 선형입니다.\n- EVM의 메모리 모델을 개선하기 위해 [EIP-3337](/eip-3337/)(프레임 포인터 방식 메모리 로드와 스토어)과 함께 제안되었습니다.\n- 페이지 경계를 넘는 정렬되지 않은 32바이트 로드/스토어를 하는 프로그램은 조금 더 내게 됩니다. 저자들은 영향을 받는 컨트랙트가 많지 않으리라 예상했습니다.\n- 명세의 테스트 케이스는 TBD로 되어 있습니다.\n"},"zh":{"lang":"zh","tldr":"提议把 EVM 内存从一个线性计价的数组改为按 1 KiB 分页、仅在访问时付费，这样编译器就可以把数据分散在整个地址空间，而无需为空隙付费。","tags":["evm","memory","gas","compilers","core"],"related":[3337,2929],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-3336/","markdown":"## 它解决什么问题？\n\nEVM 内存是一个从地址 0 开始的单一字节数组。你要为所访问过的**最高**地址之下的全部内存付费，成本呈二次增长：\n\n```\nCmem(a) = 3 * a + floor(a² / 512)      # a = words from 0 to the highest touched word\n```\n\n访问地址 1,000,000 就意味着要为它之下的每一个字付费，即使你从未使用它们。因此编译器会把内存紧凑排布，并且经常来回复制数据以保持紧凑。这既浪费 gas，也排除了一些常见的布局，例如把堆和栈放在不同区域。\n\n普通计算机用虚拟内存解决这个问题：一个巨大的地址空间，其中只有真正用到的页才由 RAM 支撑。EIP-3336 为 EVM 提议了一个简单版本。\n\n## 它如何运作\n\n参数：`PAGE_BITS = 10`（1,024 字节的页）和 `PAGE_BASE_COST = 96`。\n\n- 地址的高 246 位是页号；低 10 位是页内偏移。\n- 页在其中任何一个字节第一次被读或写时分配（用零填充）。建议客户端用以页号为键的哈希表存储页。\n- 内存成本取决于**已分配页的数量** `p`，而不是最高地址：\n\n```\nCmem'(p) = max(96 * (p - 1) + floor(2 * (p - 1)²), 0)\n```\n\n  第一页是免费的，并且曲线的设计保证在相同内存量下，收费永远不会超过现行公式。\n- 当 32 字节的字位于同一页内时，`MLOAD`/`MSTORE` 仍为 3 gas，但如果跨越两页则为 6 gas，用来支付拆分所需的额外工作。\n- 其他所有会访问内存的操作码（`CALLDATACOPY`、`CODECOPY`、`CALL`、`CREATE`、`MSTORE8` 等）都会分配其访问到的页，并收取新的扩展成本。\n\n## 示例代码\n\n比较稀疏访问模式下新旧内存成本（Python）：\n\n```python\nPAGE_BITS, PAGE_BASE_COST = 10, 96\nPAGE_SIZE = 1 \u003c\u003c PAGE_BITS\n\ndef old_cost(highest_byte: int) -\u003e int:\n    a = (highest_byte + 32) // 32          # words from 0 to highest touched word\n    return 3 * a + a * a // 512\n\ndef new_cost(pages: int) -\u003e int:\n    return max(PAGE_BASE_COST * (pages - 1) + 2 * (pages - 1) ** 2, 0)\n\ntouched = [0x0000, 0x10_0000]              # two words, ~1 MiB apart\npages = {addr \u003e\u003e PAGE_BITS for addr in touched}\nprint(old_cost(max(touched)))              # 2,195,587 gas\nprint(new_cost(len(pages)))                # 98 gas\n```\n\n## 需要注意\n\n- **状态：Stagnant（停滞）。** 它从未被排入任何硬分叉；EVM 内存定价仍然是从零开始的线性计价。\n- 它与 [EIP-3337](/eip-3337/)（帧指针式内存加载和存储）一起提出，以改进 EVM 的内存模型。\n- 在页边界上执行未对齐的 32 字节加载/存储的程序，需要多付一点；作者预计这只会影响少数合约。\n- 规范的测试用例标注为 TBD。\n"}},"requiredBy":[3337]}
