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

