Skip to content
Back to Curriculum
GAS

Gas Optimization

Gas is the fuel for the EVM. Every opcode costs a specific amount of gas. Optimization is the art of achieving the same logic with fewer or cheaper opcodes. This is critical because high gas costs can make DApps unusable.

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

A comparison of standard vs optimized code.

Practical.sol
Loading...

Core Concepts

Cold vs Warm

First access to storage/account is expensive (Cold). Subsequent accesses are cheap (Warm).

Refunds

Freeing storage (setting to 0) used to give refunds, but now is capped.

Zero vs Non-Zero

Storing 0 is cheap. Storing non-zero is expensive.

Mental Model

The Toll Road

Driving a car (transaction). Every mile you drive costs gas. Turning on the AC (Storage) costs extra. Playing the radio (Memory) costs a little. The goal is to get to the destination carrying the same cargo, using the least fuel possible.

Under the Hood

Gas is calculated dynamically. `SSTORE` (20k/2.9k) and `SLOAD` (2.1k/100) are the main drivers. `unchecked` blocks disable overhead 0.8.0+ overflow checks.

GASSSTORESLOADJUMPDEST

Gas Analysis

The Holy Trinity of Savings.

  • • Minimize Storage Writes.
  • • Use `calldata` for read-only arguments.
  • • Cache storage variables in memory/stack.

Security Risks

Optimization shouldn't compromise readability or security.

  • ! Removing overflow checks (`unchecked`) blindly can cause massive bugs.
  • ! Complex bit-packing can make code unmaintainable.

Common Use Cases

Reducing transaction fees for users.
Fitting more complex logic into the Block Gas Limit.
Preventing Out-of-Gas errors.

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Standard Loop

21,542 gas
Tx Base Cost (21k)Opcode Execution

Unchecked Loop (Optimized)

21,230 gas
Tx Base Cost (21k)Opcode Execution
Saved 312 gas