Blockchain Smart Contracts with Solidity · Aula

Slots de Armazenamento e Otimização de Gas

Entenda como o Solidity organiza variáveis de estado em slots de armazenamento de 32 bytes e use esse conhecimento para escrever contratos eficientes em gas.

Aula 4 de 413 etapas

Slots de Armazenamento e Otimização de Gas é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 1

Declaration 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 once

Avoiding 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.

Grátis para começar

Aprenda Blockchain Smart Contracts with Solidity com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Slots de Armazenamento e Otimização de Gas” é grátis?

Sim — o texto completo de “Slots de Armazenamento e Otimização de Gas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

O que vou aprender em “Slots de Armazenamento e Otimização de Gas”?

Entenda como o Solidity organiza variáveis de estado em slots de armazenamento de 32 bytes e use esse conhecimento para escrever contratos eficientes em gas. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?

Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Slots de Armazenamento e Otimização de Gas”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?

Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Variáveis de estado e layout de armazenamento
  2. Mapeamentos e matrizes dinâmicas
  3. Eventos e geração de registros
  4. Slots de Armazenamento e Otimização de Gas
← Voltar para Blockchain Smart Contracts with Solidity