Gas Optimization Solutions
1.1 Gas Optimization Overwiew
1.2 Optimization Techniques
1.2.1 Use uint256
Instead of Smaller Integers
uint256
Instead of Smaller IntegersWhile 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
Optimized
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
memory
Instead of storage
for Temporary VariablesWhen 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
SSTORE
OperationsEach 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
immutable
and constant
VariablesConstants 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
Constants:
name
,symbol
, anddecimals
are marked asconstant
, saving gas by storing them in bytecode.Immutable Total Supply: The
totalSupply
is set asimmutable
, reducing storage cost.Efficient Transfers:
balanceOf
andtransfer
methods use memory variables to minimize repeated storage access.
Last updated