Skip to main content
Writing to storage is the most expensive thing a Solidity contract does. Every write costs gas, and a larger storage footprint raises both deployment and execution costs. peaq runs a standard EVM, so the optimizations that apply on Ethereum apply here too.

Prerequisites

  • Solidity basics.
  • How the EVM handles storage, memory, and calldata, and what each costs in gas.

Optimizations

Use mappings instead of arrays

Dynamic arrays need extra operations to manage (iteration, boundary checks) and can grow unbounded. A mapping suits sparse or keyed data. Keep an array when you need to iterate over every element or read the length.
TestMapping suits sparse data and skips the bounds checks an array needs. A separate counter (itemCount) tracks indices when you want array-like ordering.

Pack variables into slots

The EVM stores data in 256-bit slots. Variables smaller than a slot share one slot when they are declared next to each other.
Group small types together and order them to fill each 256-bit slot. Fewer slots means fewer SSTORE operations and lower gas.

Use events for data you do not read on chain

Data you only need for history or off-chain display does not have to sit in storage. Emitting an event is cheaper, and the data stays retrievable from the transaction logs.
Contracts cannot read event data, only off-chain indexers can, so move data to events only if your contract never needs it again. See indexing solutions for querying events.

Use bytes for variable-length data

For strings and other variable-length data, one bytes array packs the bytes continuously, with no space wasted per element.

Cut storage reads and writes

Each SSTORE costs gas, so write once instead of repeatedly:
  • Cache a frequently updated value in memory and write it back once.
  • Read a slot into a local variable rather than reading it several times in the same function. A memory read is far cheaper than a storage read.

Reset storage slots to zero

The EVM refunds gas when you clear a storage slot, that is, when you write zero to a slot that was non-zero. The refund is capped at a share of the transaction’s gas, so the saving is partial but real on large transactions.

Use structs

Grouping related variables into a struct keeps the data together and follows the same packing rules: fields smaller than 256 bits share a slot when they are declared next to each other.