Page cover

Gas Optimization Solutions

1.1 Gas Optimization Overwiew

Gas optimization involves refining code to minimize the amount of gas required to execute a function or transaction on the blockchain. In Ethereum, each operation has a cost in gas units, which directly translates into fees. Common optimizations focus on reducing the use of storage, minimizing computational operations, and using efficient data structures.


1.2 Optimization Techniques

1.2.1 Use uint256 Instead of Smaller Integers

While using smaller integers (e.g., uint8, uint16) might seem like it would reduce gas costs, it can actually increase costs unless multiple variables are packed into a single storage slot. In general, using uint256 is the most gas-efficient for operations unless explicit storage packing is implemented.

Inefficient

uint8 smallInt; // Avoid if not packed
uint16 anotherSmallInt;

Optimized

uint256 optimizedInt; // Prefer `uint256` for independent storage variables

1.2.3 Pack Storage Variables

Storage on Ethereum is divided into 32-byte slots. By combining variables that are smaller than 32 bytes (like uint8, uint16, bool), multiple variables can share a single storage slot, reducing gas costs.

Optimized

1.2.4 Use memory Instead of storage for Temporary Variables

When working with temporary data, use memory rather than storage. memory variables are cheaper since they don’t persist on the blockchain.

Inefficient

Optimized

1.2.4 Minimize SSTORE Operations

Each time a value is written to storage (SSTORE), it incurs significant gas costs. Where possible, reduce writes to storage by performing calculations in memory and only writing the final result.

Inefficient

Optimized

1.2.5 Use immutable and constant Variables

Constants and immutables are stored in bytecode, saving storage gas costs. Use constant for values known at compile time and immutable for values set in the constructor.

1.2.6 Efficient Loops and Data Structures

Avoid unbounded loops and consider more efficient data structures. For instance, avoid looping through large arrays stored on-chain.


1.3 Code for Gas-Optimized Contracts

Gas-Optimized ERC20 Token Contract

Explanation of Optimizations

  1. Constants: name, symbol, and decimals are marked as constant, saving gas by storing them in bytecode.

  2. Immutable Total Supply: The totalSupply is set as immutable, reducing storage cost.

  3. Efficient Transfers: balanceOf and transfer methods use memory variables to minimize repeated storage access.

Last updated