Skip to content

Gas Optimization

Gas Optimization

Gas optimization refers to the process of writing efficient code and adopting specific design patterns when developing Ethereum smart contracts to reduce the Gas consumption required for contract deployment and execution.

Problem It Solves

On the Ethereum network, every line of code execution and every piece of stored data requires paying Gas. Due to limited block space and fluctuating Gas prices, inefficient contract code leads to extremely expensive transaction costs, degrades user experience, and can even cause transactions to fail due to insufficient Gas. Gas optimization aims to minimize these costs while ensuring contract functionality and security.

Implementation Mechanisms and Principles

Gas optimization primarily revolves around reducing the number of EVM opcode executions and decreasing the frequency of expensive operations (such as storage read/write SSTORE/SLOAD).

Common optimization techniques include: 1. Storage Packing: * EVM storage slots are 32 bytes (256 bits) in size. * By declaring multiple small variables (such as uint128, address, bool) sequentially, the Solidity compiler will pack them into the same slot. * This way, only a single SLOAD or SSTORE operation is needed for reading or writing, significantly saving Gas. 2. Unchecked Arithmetic: * Solidity 0.8+ enables overflow checks by default, which consumes additional Gas. * In loops or scenarios where overflow is guaranteed not to occur, you can use the unchecked { ... } code block to skip these checks. 3. Using Calldata Instead of Memory: * For array or struct parameters of external functions, use the calldata keyword instead of memory, because calldata is read-only and reads directly from the transaction input, which is cheaper than copying to memory. 4. Inline Assembly: * Use assembly { ... } to write Yul code directly, bypassing some Solidity overhead and directly manipulating the EVM stack and memory. 5. Avoiding Expensive Loops: * Minimize the number of loop iterations and avoid performing storage write operations within loops. 6. Using Constants and Immutables: * Use the constant and immutable keywords, whose values are determined at compile time or deployment time and are directly embedded in the bytecode, requiring no storage slot access when reading.

While performing Gas optimization, it is important to note the complexity trade-off: over-optimization (especially when using assembly) can reduce code readability and security.

  • Gas Optimization Handbook
  • EVM Opcodes: The instruction set of the Ethereum Virtual Machine, where each instruction has a corresponding Gas cost.
  • Storage Slot: The basic unit of EVM permanent storage.
  • Optimizer: The built-in optimizer of the Solidity compiler, which can be enabled at compile time.