📢 Exclusive on Gate Square — #PROVE Creative Contest# is Now Live!
CandyDrop × Succinct (PROVE) — Trade to share 200,000 PROVE 👉 https://www.gate.com/announcements/article/46469
Futures Lucky Draw Challenge: Guaranteed 1 PROVE Airdrop per User 👉 https://www.gate.com/announcements/article/46491
🎁 Endless creativity · Rewards keep coming — Post to share 300 PROVE!
📅 Event PeriodAugust 12, 2025, 04:00 – August 17, 2025, 16:00 UTC
📌 How to Participate
1.Publish original content on Gate Square related to PROVE or the above activities (minimum 100 words; any format: analysis, tutorial, creativ
Detailed Explanation of Gas Optimization for Ethereum Smart Contracts: 10 Practical Tips
Ethereum smart contracts Gas optimization best practices
The Gas fees on the Ethereum mainnet have always been a thorny issue, especially during network congestion. Users need to pay exorbitant transaction fees during peak times. Therefore, optimizing Gas fees during the smart contracts development phase is crucial. Reducing Gas consumption not only effectively lowers transaction costs but also enhances transaction efficiency, providing users with a more economical and efficient blockchain experience.
This article will outline the Gas fee mechanism of the Ethereum Virtual Machine (EVM), the core concepts of Gas fee optimization, and best practices for optimizing Gas fees when developing smart contracts. It is hoped that this content can inspire and provide practical assistance to developers, while also helping ordinary users better understand the operation of EVM's Gas fees, collectively addressing the challenges in the blockchain ecosystem.
Introduction to the Gas Fee Mechanism of EVM
In EVM-compatible networks, "Gas" is the unit used to measure the computational power required to execute specific operations.
In the structure layout of the EVM, gas consumption is divided into three parts: operation execution, external message calls, and reading and writing of memory and storage.
Since each transaction execution requires computational resources, a certain fee will be charged to prevent infinite loops and denial of service ( DoS ) attacks. The fee required to complete a transaction is called "Gas fee".
Since the EIP-1559( London hard fork ) took effect, the Gas fee is calculated using the following formula:
Gas fee = units of gas used * ( base fee + priority fee )
The base fee will be burned, while the priority fee will serve 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" paid by users to validators.
Understanding Gas optimization in EVM
When compiling smart contracts with Solidity, the contracts are converted into a series of "operation codes", or opcodes.
Any piece of opcode (, such as creating contracts, making message calls, accessing account storage, and executing operations on the virtual machine ), has a recognized Gas consumption cost, which is recorded in the Ethereum yellow paper.
After multiple modifications to the EIP, the Gas costs of some opcodes have been adjusted and may differ from those in the yellow paper.
Basic concepts of Gas optimization
The core concept of Gas optimization is to prioritize cost-efficient operations on the EVM blockchain and avoid operations with high Gas costs.
In the EVM, the following operations are relatively low-cost:
The high-cost operations include:
Best Practices for EVM Gas Fee Optimization
Based on the aforementioned basic concepts, we have compiled a best practices checklist for gas fee optimization for the developer community. By following these practices, developers can reduce the gas fee consumption of smart contracts, lower transaction costs, and create more efficient and user-friendly applications.
1. Try to minimize storage usage.
In Solidity, Storage( storage) is a limited resource, with Gas consumption much higher than Memory( 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 consume only 3 gas units, while storage operations such as sload and sstore cost at least 100 units even under the most ideal circumstances.
Methods to limit storage usage include:
2. Variable Packaging
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 consecutive storage variables during the compilation process, using a 32-byte storage slot as the basic unit for variable storage. Variable packing refers to the arrangement of variables in such a way that multiple variables can fit into a single storage slot.
By adjusting this detail, developers can save 20,000 gas units. Storing an unused storage slot requires 20,000 gas, but now only two storage slots are needed.
Since each storage slot consumes Gas, variable packing optimizes Gas usage by reducing the number of storage slots required.
![Top 10 Best Practices for Gas Optimization of Ethereum smart contracts])https://img-cdn.gateio.im/webp-social/moments-995905cb414526d4d991899d0c2e6443.webp(
) 3. Optimize data types
A variable can be represented by multiple data types, but the operational cost associated with different data types varies. Choosing the appropriate data type helps optimize the use of Gas.
For example, in Solidity, integers can be subdivided into different sizes: uint8, uint16, uint32, etc. Since the EVM executes operations in 256-bit units, using uint8 means the EVM must first convert it to uint256, and this conversion will consume extra Gas.
Individually, using uint256 is cheaper than uint8. However, it is different if we utilize the variable packing optimization we suggested earlier. If developers can pack four uint8 variables into one storage slot, then the total cost of iterating over them will be lower than that of four uint256 variables. In this way, the smart contracts can read and write to a storage slot once, and place the four uint8 variables into memory/storage in a single 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
The data list in Solidity can be represented by two data types: Arrays ) and Mappings ###, but their syntax and structure are completely different.
In most cases, mappings are more efficient and cost-effective, but arrays are iterable and support data type packing. Therefore, it is recommended to prioritize the use of mappings when managing data lists, unless iteration is required or Gas consumption can be optimized through data type packing.
![Top 10 Best Practices for Gas Optimization in Ethereum smart contracts]###https://img-cdn.gateio.im/webp-social/moments-5f3d7e103e47c886f50599cffe35c707.webp(
) 6. Use calldata instead of memory
Variables declared in function parameters can be stored in calldata or memory. The main difference between the two is that memory can be modified by the function, while calldata is immutable.
Remember this principle: if the function parameters are read-only, prefer using calldata over memory. This can avoid unnecessary copy operations from function calldata to memory.
( 7. Try to use the Constant/Immutable keywords as much as possible.
Constant/Immutable variables are not stored in the contract's storage. These variables are computed at compile time and stored in the contract's bytecode. Therefore, their access cost is much lower compared to storage, and it is recommended to use the Constant or Immutable keywords whenever possible.
![Top 10 Best Practices for Gas Optimization of Ethereum Smart Contracts])https://img-cdn.gateio.im/webp-social/moments-9c566626ab499ef65d6f5089a2876ad3.webp(
) 8. Use Unchecked to ensure that overflow/underflow will not occur.
When developers can ensure that arithmetic operations will not result in overflow or underflow, they can use the unchecked keyword introduced in Solidity v0.8.0 to avoid unnecessary overflow or underflow checks, thereby saving Gas costs.
In addition, compilers version 0.8.0 and above no longer require the use of the SafeMath library, as the compiler itself has built-in overflow and underflow protection features.
9. Optimizer
The code of the modifier is embedded into the modified function, and every time the modifier is used, its code is copied. This increases the size of the bytecode and raises Gas consumption.
By restructuring the logic into the internal function _checkOwner###(, allowing the internal function to be reused in the modifier, the bytecode size can be reduced and Gas costs lowered.
![Ethereum smart contracts Gas optimization top ten best practices])https://img-cdn.gateio.im/webp-social/moments-c0701f9e09280a1667495d54e262dd2f.webp###
10. Short-circuit optimization
For the || and && operators, logical operations will undergo short-circuit evaluation, meaning that if the first condition can already determine the result of the logical expression, the second condition will not be evaluated.
To optimize Gas consumption, conditions with low computational costs should be placed first, as this may allow for skipping costly computations.
Additional General Recommendations
( 1. Remove unused 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 the contract size small.
Here are some practical suggestions:
Use the most efficient algorithms for calculations. If the results of certain calculations are directly used in the contract, then redundant calculation processes should be eliminated. Essentially, any unused calculations should be removed.
In Ethereum, 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 its default value.
Loop optimization: avoid high-cost loop operations, merge loops whenever possible, and move repeated calculations out of the loop body.
![Top 10 Best Practices for Gas Optimization of Ethereum smart contracts])https://img-cdn.gateio.im/webp-social/moments-839b91e2f02389949aa698d460a497d8.webp###
( 2. Using pre-compiled contracts
Precompiled contracts provide complex library functions, such as encryption and hashing operations. Since the code runs locally on client nodes rather than on the EVM, less Gas is required. Using precompiled contracts can save Gas by reducing the computational workload 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 reduce Gas costs and improve the operational efficiency of applications.
( 3. Use inline assembly code
In-line assembly ) allows developers to write low-level yet efficient code that can be executed directly by the EVM, without the need to use expensive Solidity opcodes. In-line assembly also allows for more precise control over memory and storage usage, further reducing gas costs. Additionally, in-line assembly can perform some complex operations that are difficult to achieve using only Solidity, providing more flexibility for optimizing gas consumption.
However, using inline assembly can also pose risks and is prone to errors. Therefore, it should be used with caution and limited to experienced developers.
![Top 10 Best Practices for Gas Optimization in Ethereum smart contracts]###https://img-cdn.gateio.im/webp-social/moments-a141884dcdcdc56faff12eee2601b7b7.webp(
) 4.