freecoding.school100% FREE · NO SIGNUP
The EVM CoreISSUE #15 of 48

memory expansion · quadratic cost

SoliaVSThe Reentrancy Reaper
Solia saysEVM memory expansion has a quadratic-in-size cost — 3·words + words²/512 — so doubling memory more than doubles the gas spent on it.

EVM memory grows on demand: the first byte you touch beyond the current size triggers memory expansion, and you pay for the new total size up front. The formula is cost(words) = 3·words + ⌊words²/512⌋ where one word = 32 bytes. For small sizes the linear term dominates; past ~10,000 words the quadratic term takes over and gas grows fast.

That is why dApps that load huge arrays in-memory die at runtime — the quadratic term punishes naive scaling. Pre-allocating or streaming through small windows keeps the cost linear. The demo computes the cost across six sizes from 1 word to 100,000 words.

Power-ups you unlock

The Reentrancy Reaper attacks — common mistakes

Boss battleCompute the EVM memory expansion cost for 1, 100, 1000, 10000, and 100000 words and confirm the quadratic dominates at the high end.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>
// real EVM formula: cost(words) = 3*words + floor(words^2 / 512)
const memCost = (w) => 3 * w + Math.floor(w * w / 512);
const sizes = [1, 32, 100, 1000, 10000, 100000];
const rows = sizes.map(w => {
  const linear = 3 * w;
  const quad   = Math.floor(w * w / 512);
  return 'words=' + String(w).padStart(7) + '  bytes=' + String(w*32).padStart(9) + '  cost=' + memCost(w).toLocaleString().padStart(13) + '  (linear=' + linear.toLocaleString() + ' + quad=' + quad.toLocaleString() + ')';
});
document.getElementById('o').textContent = [
  'EVM memory expansion: cost = 3·words + ⌊words²/512⌋',
  '',
  ...rows,
  '',
  'past ~10K words the quadratic term overtakes the linear → fast gas blowup'
].join('\n');
</script></body></html>
▶ Open the interactive comic issue
‹ Gas Costs · Per-Opcode AccountingStorage Slots · Packing · Refunds ›