Blockchain Smart Contracts with Solidity · Урок

Ячейки хранилища и оптимизация расхода газа

Разберитесь, как Solidity размещает переменные состояния в ячейках хранилища размером 32 байта, и используйте эти знания для создания контрактов с эффективным расходом газа.

Урок 4 из 413 шагов

«Ячейки хранилища и оптимизация расхода газа» — бесплатный урок Blockchain Smart Contracts with Solidity на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Blockchain Smart Contracts with Solidity, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Blockchain Smart Contracts with Solidity содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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.

Можно начать бесплатно

Изучай Blockchain Smart Contracts with Solidity с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Ячейки хранилища и оптимизация расхода газа» бесплатный?

Да — полный текст урока «Ячейки хранилища и оптимизация расхода газа» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Blockchain Smart Contracts with Solidity, подпишись на CoddyKit PRO. Курс Blockchain Smart Contracts with Solidity содержит 4 уроков всего.

Чему я научусь в уроке «Ячейки хранилища и оптимизация расхода газа»?

Разберитесь, как Solidity размещает переменные состояния в ячейках хранилища размером 32 байта, и используйте эти знания для создания контрактов с эффективным расходом газа. Ты практикуешь Blockchain Smart Contracts with Solidity с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Blockchain Smart Contracts with Solidity?

Предыдущий опыт не требуется. Blockchain Smart Contracts with Solidity на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Ячейки хранилища и оптимизация расхода газа»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Blockchain Smart Contracts with Solidity?

Да. Каждый урок Blockchain Smart Contracts with Solidity включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Переменные состояния и размещение в хранилище
  2. Отображения и динамические массивы
  3. События и журналирование данных
  4. Ячейки хранилища и оптимизация расхода газа
← Назад к Blockchain Smart Contracts with Solidity