Slots de almacenamiento y optimización de gas
Comprenda cómo Solidity distribuye las variables de estado en slots de almacenamiento de 32 bytes y utilice ese conocimiento para escribir contratos eficientes en gas.
Slots de almacenamiento y optimización de gas es una lección gratuita de Blockchain Smart Contracts with Solidity en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Blockchain Smart Contracts with Solidity, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Storage Costs Matter
Writing to contract storage is one of the most expensive operations on Ethereum. Understanding the storage layout lets you reduce slots written and save users real money.
The 32-Byte Slot
Contract storage is an array of slots, each 32 bytes (256 bits). State variables are assigned to slots in declaration order, starting at slot 0.
Variable Packing
Multiple small variables that fit within 32 bytes are packed into the same slot. A uint128 and another uint128 share one slot, halving storage writes if updated together.
uint128 a; // slot 0
uint128 b; // slot 0 (packed)
uint256 c; // slot 1Declaration Order Matters
Packing only works for adjacent variables that fit. Poor ordering wastes slots. Group small types together rather than interleaving them with full-size uint256 variables.
Bad vs Good Ordering
Interleaving a small type between large ones prevents packing and uses extra slots.
// Bad: 3 slots
uint128 x;
uint256 y;
uint128 z;
// Good: 2 slots
uint256 y;
uint128 x;
uint128 z;Mappings and Dynamic Arrays
Mappings and dynamic arrays do not pack. Their slot holds metadata, and actual values are stored at hashed locations. Each element write is its own storage cost.
Constants and Immutables
Values marked constant or immutable are stored in the contract bytecode, not in storage slots. Reading them is far cheaper than reading a state variable.
uint256 public constant MAX = 1000;
address public immutable owner;Caching Storage in Memory
Reading the same storage variable repeatedly inside a loop is wasteful. Cache it in a memory local variable once, operate on it, then write back once.
uint256 total = balance; // read once
for (uint i; i < n; i++) total += amounts[i];
balance = total; // write onceAvoiding Redundant Writes
Writing a value identical to the current one still costs gas. Skip a storage write if the new value equals the existing one, or only update when something actually changed.
Cheaper Storage Refunds
Clearing a storage slot back to zero gives a partial gas refund. Patterns that delete unused entries can reclaim some cost, though refund rules have changed across network upgrades.
Measuring Gas Usage
Use a gas reporter to see the cost of each function. Optimize the hottest, most-called functions first; micro-optimizing rarely-used code is not worth the readability cost.
Quick Check
Check your storage optimization knowledge.
Recap
You learned to optimize contract storage:
- Storage is 32-byte slots assigned in declaration order
- Pack small adjacent variables to share slots
- Use constant/immutable for fixed values
- Cache storage in memory, avoid redundant writes, and measure gas
Smart storage layout directly lowers the cost of using your contract.
Aprende Blockchain Smart Contracts with Solidity con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Slots de almacenamiento y optimización de gas» es gratis?
Sí — el texto completo de «Slots de almacenamiento y optimización de gas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Blockchain Smart Contracts with Solidity, actualiza a CoddyKit PRO. El curso de Blockchain Smart Contracts with Solidity incluye 4 lecciones en total.
¿Qué aprenderé en «Slots de almacenamiento y optimización de gas»?
Comprenda cómo Solidity distribuye las variables de estado en slots de almacenamiento de 32 bytes y utilice ese conocimiento para escribir contratos eficientes en gas. Practicas Blockchain Smart Contracts with Solidity con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Blockchain Smart Contracts with Solidity?
No se requiere experiencia previa. Blockchain Smart Contracts with Solidity en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Slots de almacenamiento y optimización de gas»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Blockchain Smart Contracts with Solidity?
Sí. Cada lección de Blockchain Smart Contracts with Solidity incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Variables de estado y distribución del almacenamiento
- Mappings y arrays dinámicos
- Eventos y registro de datos
- Slots de almacenamiento y optimización de gas