Futures
Access hundreds of perpetual contracts
CFD
Gold
One platform for global traditional assets
Options
Hot
Trade European-style vanilla options
Unified Account
Maximize your capital efficiency
Demo Trading
Introduction to Futures Trading
Learn the basics of futures trading
Futures Events
Join events to earn rewards
Demo Trading
Use virtual funds to practice risk-free trading
Launch
CandyDrop
Collect candies to earn airdrops
Launchpool
Quick staking, earn potential new tokens
HODLer Airdrop
Hold GT and get massive airdrops for free
IPO Access
Unlock full access to global stock IPOs
Alpha Points
Trade on-chain assets and earn airdrops
Futures Points
Earn futures points and claim airdrop rewards
Promotions
AI
Gate AI
Your all-in-one conversational AI partner
Gate AI Bot
Use Gate AI directly in your social App
GateClaw
Gate Blue Lobster, ready to go
Gate for AI Agent
AI infrastructure, Gate MCP, Skills, and CLI
Gate Skills Hub
10K+ Skills
From office tasks to trading, the all-in-one skill hub makes AI even more useful.
GateRouter
Smartly choose from 40+ AI models, with 0% extra fees
Top 10 Best Practices for Gas Optimization in Ethereum Smart Contracts
The Gas fees on the Ethereum Mainnet have always been a major issue, especially more significant during network congestion. During peak periods, users often need to pay extremely high Transaction Cost. Therefore, optimizing Gas consumption during the Smart Contract development phase is particularly important. Optimizing Gas consumption can not only effectively reduce Transaction Cost, but also improve transaction efficiency, bringing users a more economical and efficient blockchain usage experience.
This article will outline the Gas fee mechanism of the ETH network virtual machine (EVM), core concepts of Gas fee optimization, and best practices for optimizing Gas fees when developing Smart Contracts. It is hoped that through these contents, developers can be inspired and practically assisted, while also helping ordinary users better understand the operation of Gas fees in the EVM and jointly address the challenges in the blockchain ecosystem.
Introduction to Gas Fee Mechanism of EVM
In EVM-compatible networks, "Gas" refers to the unit used to measure the computational power required to perform specific operations.
The diagram below illustrates the structure layout of EVM. In the diagram, Gas consumption is divided into three parts: operation execution, external message calls, and reading and writing of memory and storage.
Because the execution of each transaction requires computational resources, a certain fee is charged to prevent infinite loops and denial-of-service (DoS) attacks. The fee required to complete a transaction is called "Gas fee".
Since the implementation of EIP-1559 (London Hard Fork), the gas fee is calculated by the following formula:
Gas fee = units of gas used * (base fee + priority fee)
The base fee will be destroyed, while the priority fee serves as an incentive to encourage validators to add transactions to the blockchain. Setting a higher priority fee when sending a transaction can increase the likelihood of the transaction being included in the next block. This is similar to a 'tip' that users pay to validators.
1. Understanding Gas Optimization in EVM
When compiling a Smart Contract with Solidity, the contract is converted to a series of 'opcodes'.
Any opcode (e.g. creating contracts, making message calls, accessing account storage, and executing operations on the virtual machine) has a recognized Gas consumption cost, and these costs are recorded in the ETH Yellow Paper [2].
After multiple revisions of EIP, the Gas costs of some opcodes have been adjusted, which may deviate from the Yellow Paper. For the latest information on opcode costs, please refer to this link [3].
2. Gas optimization basic concepts
The core concept of Gas optimization is to prioritize operations with high cost efficiency on the EVM blockchain, avoiding operations with expensive Gas costs.
In EVM, the following operation costs are lower:
High-cost operations include:
EVM Gas Fee Optimization Best Practices
Based on the above basic concepts, we have compiled a Gas Fee Optimization Best Practices Checklist for the developer community. By following these practices, developers can reduce the Gas consumption of Smart Contracts, lower the Transaction Cost, and build more efficient and user-friendly applications.
1. Try to minimize storage usage
In Solidity, Storage is a finite resource whose gas consumption is much higher than Memory. Every time a Smart Contract reads or writes data from storage, it incurs high gas costs.
According to the definition in the Ethereum Yellow Paper, the cost of storage operations is more than 100 times higher than that of memory operations. For example, the OPcodes mload and mstore instructions only consume 3 Gas units, while storage operations such as sload and sstore, even in the most ideal situation, require at least 100 units of cost.
Methods to restrict storage usage include:
2. Variable Packing
The number of storage slots used in Smart Contracts and the way developers represent data will greatly affect the consumption of Gas fees.
The Solidity compiler will pack continuous storage variables during the compilation process and use a 32-byte storage slot as the basic unit for variable storage. Variable packing refers to arranging variables in a way that multiple variables can fit into a single storage slot.
The left is a less efficient implementation that consumes 3 storage slots; the right is a more efficient implementation.
By making this adjustment, developers can save 20,000 gas units (storing an unused storage slot consumes 20,000 gas), but now only two storage slots are needed.
As each storage slot consumes gas, variable packing optimizes gas usage by reducing the number of required storage slots.
3. Optimize Data Types
A variable can be represented in multiple data types, but the cost of operations for different data types is also different. Choosing the appropriate data type helps optimize Gas usage.
For example, in Solidity, integers can be divided into different sizes: uint8, uint16, uint32, etc. Since the EVM operates in 256-bit units, using uint8 means that the EVM must first convert it to uint256, which incurs additional gas consumption.
We can compare the Gas costs of uint8 and uint256 in the code in the figure. The UseUint() function consumes 120,382 Gas units, while the UseUInt8() function consumes 166,111 Gas units.
Looking at it in isolation, using uint256 here is cheaper than uint8. However, it's different if you use the variable packing optimization we suggested earlier. If the developer can pack four uint8 variables into one storage slot, then the total cost of iterating through them will be lower than four uint256 variables. This way, the Smart Contract can read and write to a storage slot once and put four uint8 variables into memory/storage in one operation.
4. Use fixed-size variables instead of dynamic variables
If the data can be controlled within 32 bytes, it is recommended to use the bytes32 data type instead of bytes or strings. Generally speaking, fixed-size variables consume less gas than variable-size variables. If the byte length can be limited, try to choose the minimum length from bytes1 to bytes32.
5. Mapping and Arrays
Solidity's data list can be represented by two data types: arrays and mappings, but their syntax and structure are completely different.
Mapping is generally more efficient and cost-effective, but arrays are iterable and support data type packing. Therefore, it is recommended to prioritize using mapping when managing data lists, unless iteration is required or gas consumption can be optimized through data type packing.
6. Use calldata instead of memory
Variables declared in function arguments can be stored in calldata or memory. The main difference between the two is that memory can be modified by functions, while calldata is immutable.
Remember this principle: if the function parameters are read-only, calldata should be used instead of memory. This can avoid unnecessary copying from calldata to memory in the function.
Example 1: Using memory
![The Top 10 Best Practices for Gas Optimization of ETH Smart Contracts]()
When using the memory keyword, the value of the array will be copied from the encoded calldata to memory during the ABI decoding process. The execution cost of this code block is 3,694 Gas units.
Example 2: Using calldata
When directly reading values from calldata, skip the intermediate memory operations. This optimization reduces the execution cost to only 2,413 Gas units, increasing Gas efficiency by 35%.
7. Try to use the Constant/Immutable keyword as much as possible
Constant/Immutable variables are not stored in the contract's storage. These variables are calculated at compile time and stored in the contract's bytecode. Therefore, their access cost is much lower than storage, and it is recommended to use the Constant or Immutable keywords as much as possible.
8. Use Unchecked only when it is ensured that no overflow/underflow will occur
When developers can determine that arithmetic operations will not cause overflow or underflow, they can use the 'unchecked' keyword introduced in Solidity v0.8.0 to avoid redundant overflow or underflow checks, thus saving gas costs.
In the following figure, subject to the conditional constraint i
In addition, compilers version 0.8.0 and above no longer need to use the SafeMath library, as the compiler itself has built-in overflow and underflow protection.
9. Optimized Modifier
The code of the modifier is embedded in the modified function, and each time the modifier is used, its code is copied. This increases the size of the bytecode and increases gas consumption. Here is a method to optimize the gas cost of the modifier:
Before optimization:
Optimized:
In this example, by refactoring the logic into an internal function _checkOwner(), it allows for the reuse of this internal function in modifiers, reducing bytecode size and dropping Gas cost.
10. Short Circuit Optimization
For || and && operators, logical computation will undergo short-circuit evaluation, that is, if the result of the logical expression can be determined by the first condition, the second condition will not be evaluated.
To optimize gas consumption, the conditions with low computation cost should be placed at the front, so as to potentially skip the expensive computation.
Additional General Advice
1. Remove unnecessary code
If there are unused functions or variables in the contract, it is recommended to delete them. This is the most direct way to reduce contract deployment costs and keep contract size small.
Here are some practical suggestions:
Use the most efficient algorithm for calculation. If certain calculation results are directly used in the contract, then the redundant calculation process should be removed. Essentially, any unused calculation should be eliminated.
In the ETH network, developers can earn Gas rewards by freeing up storage space. If a variable is no longer needed, it should be deleted using the delete keyword or set to a default value.
Loop Optimization: Avoid high-cost loop operations, merge loops as much as possible, and move repetitive calculations out of the loop body.
2. Using Precompiled Contracts
Precompiled contracts provide complex library functions such as encryption and hashing operations. Since the code is not executed on the EVM but locally on the client node, less gas is required. Using precompiled contracts can save gas by reducing the amount of computational work required to execute smart contracts.
Examples of precompiled contracts include the Elliptic Curve Digital Signature Algorithm (ECDSA) and the SHA2-256 hash algorithm. By using these precompiled contracts in Smart Contracts, developers can drop Gas costs and improve the efficiency of their applications.
For a complete list of precompiled contracts supported by the ETH network, please refer to this link [4].
3. Using inline assembly code
Inline assembly allows developers to write low-level but efficient code that can be directly executed by the EVM, without the need to use expensive Solidity opcodes. Inline assembly also allows for more precise control over the use of memory and storage, further reducing Gas fees. In addition, inline assembly can perform some complex operations that are difficult to achieve using Solidity alone, providing more flexibility for optimizing Gas consumption.
Here is an example of using inline assembly to save Gas:
From the above figure, it can be seen that the second use case using inline assembly technology has higher Gas efficiency compared to the standard use case.
However, using inline assembly may also bring risks and be prone to errors. Therefore, it should be used with caution and only operated by experienced developers.
4. Using Layer 2 Solutions
Using Layer 2 solutions can reduce the amount of data that needs to be stored and computed on the ETH Mainnet.
Layer 2 solutions such as rollups, sidechains, and state channels can offload transaction processing from the main Ethereum network, resulting in faster and cheaper transactions.
By bundling a large number of transactions together, these solutions reduce the number of on-chain transactions, thereby reducing Gas fees. Using Layer 2 solutions can also improve the scalability of the Ethereum network, allowing more users and applications to participate in the network without causing network congestion.
5. Using optimization tools and libraries
There are multiple optimization tools available, such as the solc optimizer, Truffle's build optimizer, and Remix's Solidity compiler.
! [Top 10 Best Practices for Gas Optimization of Smart Contract in ETH Square] (https://cdn-img.panewslab.com/yijian/2024/12/30/images/b9dc072d3e850ceeb7961a0c7469a03a.jpg)
These tools can help minimize the size of bytecode, remove unused code, and reduce the number of operations required to execute Smart Contracts. Combined with other Gas optimization libraries, such as 'solmate', developers can effectively reduce Gas costs and improve the efficiency of Smart Contracts.
Conclusion
Optimizing Gas consumption is an important step for developers, as it can minimize Transaction Cost and improve the efficiency of Smart Contracts on EVM-compatible networks. By prioritizing cost-saving operations, reducing storage usage, utilizing inline assembly, and following other best practices discussed in this article, developers can effectively reduce the Gas consumption of contracts.
However, it is important to note that developers must be cautious in the optimization process to avoid introducing security vulnerabilities. In the process of optimizing code and reducing gas consumption, the inherent security of the Smart Contract should never be sacrificed.
[1] :
[2] :
[3] :
[4] :precompiled