WTF Gas 優化#
Solidity gas 優化技術,使用 Foundry。總結寫 Solidity 智能合約更省 gas 的技巧。
大綱#
1. 使用 constant 和 immutable#
測試
forge test --contracts 01_Constant/Constant.t.sol --gas-report
Gas 報告
函數名稱 | Gas 成本 |
---|---|
varConstant | 183 |
varImmutable | 161 ✅ |
variable | 2305 |
2. 使用 calldata 而非 memory#
測試
forge test --contracts 02_CalldataAndMemory/CalldataAndMemory.T.sol --gas-report
Gas 報告
函數名稱 | Gas 成本 |
---|---|
writeByCalldata | 67905 ✅ |
writeByMemory | 68456 |
3. 使用 Bitmap#
測試
forge test --contracts 03_Bitmap/Bitmap.T.sol --gas-report
Gas 報告
函數名稱 | Gas 成本 |
---|---|
setDataWithBitmap | 22366 ✅ |
setDataWithBoolArray | 35729 |
4. 使用 unchecked#
測試
forge test --contracts 04_unchecked/Unchecked.T.sol --gas-report
Gas 報告
函數名稱 | Gas 成本 |
---|---|
forNormal | 1910309 |
forUnckecked | 570287 ✅ |
5. 使用 uint256 而非 uint8#
測試
forge test --contracts 05_uint/Uint.T.sol --gas-report
Gas 報告
函數名稱 | Gas 成本 |
---|---|
read Uint8 | 2379 |
read Uint128 | 2465 |
read Uint256 | 2317 ✅ |
set Uint8 | 5355 |
set Uint128 | 5358 |
set Uint256 | 5322 ✅ |
6. 使用自定義錯誤而非 require/assert#
測試
forge test --contracts 06_Error/Error.T.sol --gas-report
Gas 報告
錯誤名稱 | Gas 成本 |
---|---|
Assert | 180 |
Require | 268 |
Revert | 164 ✅ |
7. 使用局部變數而非存儲#
測試
forge test --contracts 07_LocalData/LocalData.T.sol --gas-report
Gas 報告
數據類型 | Gas 成本 |
---|---|
localData | 1902339 ✅ |
storageData | 4022155 |
8. 使用 clone2 而非 new/create2#
測試
forge test --contracts 08_Clone2/Clone2.T.sol --gas-report
Gas 報告
創建類型 | Gas 成本 |
---|---|
clone2 | 41493 ✅ |
create2 | 93031 |
new | 79515 |
9. 打包存儲槽#
測試
forge test --contracts 09_Packing/Packing.T.sol --gas-report
Gas 報告
創建類型 | Gas 成本 |
---|---|
normal | 133521 |
packing | 111351 ✅ |