🎉 [Gate 30 Million Milestone] Share Your Gate Moment & Win Exclusive Gifts!
Gate has surpassed 30M users worldwide — not just a number, but a journey we've built together.
Remember the thrill of opening your first account, or the Gate merch that’s been part of your daily life?
📸 Join the #MyGateMoment# campaign!
Share your story on Gate Square, and embrace the next 30 million together!
✅ How to Participate:
1️⃣ Post a photo or video with Gate elements
2️⃣ Add #MyGateMoment# and share your story, wishes, or thoughts
3️⃣ Share your post on Twitter (X) — top 10 views will get extra rewards!
👉
Ethereum smart contracts Gas optimization guide: drop transaction cost and improve efficiency
Ethereum smart contracts Gas optimization guide
The Gas fees on the Ethereum mainnet have always been a tricky issue, especially during times of network congestion. During peak periods, users often have to pay exorbitant transaction fees. Therefore, optimizing Gas costs during the smart contracts development phase becomes 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 overview 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 will inspire and provide practical help to developers, while also helping ordinary users better understand the operation of EVM's Gas fees, collectively addressing the challenges within 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 EVM structure, gas consumption is mainly divided into three parts: operation execution, external message calls, and reading and writing memory and storage.
Since each transaction execution requires computing 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 ) came into effect, Gas fees are calculated using the following formula:
Gas fee = Gas units used * ( base fee + priority fee )
The base fee will be burned, 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" paid by users to validators.
Understanding Gas optimization in EVM
When compiling smart contracts with Solidity, the contract is converted into a series of "operation codes", or opcodes.
Any segment 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 idea of Gas optimization is to prioritize cost-effective operations on the EVM blockchain, avoiding operations with high Gas costs.
In the EVM, the following operations have a lower cost:
The operations with higher costs include:
Best Practices for EVM Gas Fee Optimization
Based on the above basic concepts, we have compiled a list of best practices 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, and its Gas consumption is much higher than Memory( memory). Each time a smart contract reads from or writes to storage, it incurs high Gas costs.
According to the definition in the Ethereum yellow paper, the cost of storage operations is over 100 times higher than that of memory operations. For example, the OPcodes mload and mstore instructions consume only 3 gas units, while storage operations like sload and sstore, even in the most ideal case, require at least 100 units.
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 32-byte storage slots as the basic unit for variable storage. Variable packing refers to the reasonable arrangement of variables so 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 costs associated with different data types vary. 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 that the EVM must first convert it to uint256, and this conversion will incur additional Gas costs.
Individually, using uint256 is cheaper than uint8 here. However, it is different if we use the variable packing optimization we suggested earlier. If developers can pack four uint8 variables into a single storage slot, the total cost of iterating through them will be lower than that of 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 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 smallest length from bytes1 to bytes32.
5. Mapping and Arrays
The data list in Solidity can be represented using two data types: Arrays( and Mappings), but their syntax and structure are completely different.
Mappings are generally more efficient and cost-effective in most cases, but arrays have iterability 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 of Ethereum smart contracts]###https://img-cdn.gateio.im/webp-social/moments-9c566626ab499ef65d6f5089a2876ad3.webp(
) 6. Use calldata instead of memory
Variables declared in the 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. 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 in Ethereum smart contracts])https://img-cdn.gateio.im/webp-social/moments-a823fb7761aafa6529a6c45304e0314b.webp###
( 8. Use Unchecked when ensuring that overflow/underflow will not occur.
When developers can ensure that arithmetic operations will not cause overflow or underflow, they can use the unchecked keyword introduced in Solidity v0.8.0 to avoid unnecessary overflow or underflow checks, thus 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.
![Top 10 Best Practices for Gas Optimization of Ethereum smart contracts])https://img-cdn.gateio.im/webp-social/moments-839b91e2f02389949aa698d460a497d8.webp###
( 9. Optimizer
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 raises Gas consumption.
By restructuring the logic into the internal function _checkOwner)###, it allows for the reuse of this internal function within the modifier, which can reduce bytecode size and lower gas costs.
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, which may allow for skipping expensive computations.
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 the contract size small.
Here are some practical suggestions:
Use the most efficient algorithms for calculations. If the results of certain calculations are used directly in the contract, then those redundant calculation processes should be removed. Essentially, any unused calculations should be deleted.
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.
) 2. Use precompiled smart contracts
Precompiled contracts provide complex library functions, such as encryption and hashing operations. Since the code runs locally on the client node rather than on the EVM, it requires less Gas. 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 efficiency of their applications.
3. Using inline assembly code
Inline 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. Inline assembly also allows for more precise control over memory and storage usage, further reducing Gas fees. In addition, inline 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 may also bring risks.