Gas Fee Comparison Among Difference Keyword
Abstract
Gas optimization is extremely important to minimize the cost of deployment and gas fees for the end user. This article demonstrates a series of testings to compare the gas fee of varying keyword.
The unit testing code released at .
Evaluation Setting
The hardhat gas reporter plugin is used in this research for gas estimation.
|
|
The configuration of hardhat-gas-reporter is listed as follows:
|
|
Option: Estimate the gas fee in USD
Here is way to transfer gas fee to USD currency in realtime, we get the currency information from coinmarketcap.
Add dotenv to your environment.
|
|
Add dotenv and hardhat-gas-reporter to hardhat.config.js
.
|
|
Create a .env
file in root folder, add following string.
The {Your CoinMacketCap API KEY} is
|
|
The {Your CoinMacketCap API KEY}
can be obtained by registering an account at https://pro.coinmarketcap.com/ .
Constant, Immutable, Variable comparison
We defind three value using Constant, Immutable, Variable keyword.
For each keyword value, addVarC()
, addVarI()
, and addVarV()
are used to read the corresponding keyword value and assign it to the a variable.
We list code as follow.
|
|
In solidity, the MethodID order of the functions will effect the gas fee. The later the sort will consume more. Each position will have an extra 22 gas.
Here is the MethodID order of the functions in this example:
|
|
Therefore, we run the unit testing, the result of gas fee are list following:
Method | Gas Fee | Net Gas Fee | Save(Compare to varibale) |
---|---|---|---|
addVarC | 23400 | 23400 | 66 |
addVarI | 43422 | 23400 | 66 |
AddVarV | 23510 | 23466 | 0 |
Due to the limitation of hardhat, I can’t achieve the cost of single read.
Here are the pure reading result in remix ide:
Keywork | Net Gas Fee | Save(Compare to varibale) |
---|---|---|
constant | 161 | 2100 (≈93%) |
immutable | 161 | 2100 (≈93%) |
variable | 2261 | 0 |
Conclusion
- In practical, The variable definitions should be avoided as much as possible;
- For constants that do not need to be modified, it is recommended to use const to define them, which is the best in terms of functionality and gas.
Calldata, Memory comparison
This section compares Calldata
and Memory
keywords.
We write same data to variables modified in calldata and memory respectively.
|
|
Here is the result of gas fee:
Gas fee comparision of calldata and memory.
Method | Gas Fee | Net Gas Fee | Save(Compare to writeByCalldata) |
---|---|---|---|
writeByCalldata | 91372 | 91372 | 0 |
writeByMemory | 92164 | 92142 | 770 (≈0.8%) |
Conclusion
- It is recommended to use
calldata
for variable writing in preference.