Solidity gas optimization techniques, using Foundry. 总结写 Solidity 智能合约更省 gas 的技巧。
Lead by @kasodesyn
6. use custom error over require/assert
7. use local variable over storage
8. use clone2 over new/create2
10. use ++i as better increment
11. use uint in reentrancy guard
Testing
forge test --contracts 01_Constant/Constant.t.sol --gas-report
Gas report
| Function Name | Gas Cost |
|---|---|
| varConstant | 183 ✅ |
| varImmutable | 161 ✅ |
| variable | 2305 |
Testing
forge test --contracts 02_CalldataAndMemory/CalldataAndMemory.T.sol --gas-report
Gas report
| Function Name | Gas Cost |
|---|---|
| writeByCalldata | 67905 ✅ |
| writeByMemory | 68456 |
Testing
forge test --contracts 03_Bitmap/Bitmap.T.sol --gas-report
Gas report
| Function Name | Gas Cost |
|---|---|
| setDataWithBitmap | 22366 ✅ |
| setDataWithBoolArray | 35729 |
Testing
forge test --contracts 04_unchecked/Unchecked.T.sol --gas-report
Gas report
| Function Name | Gas Cost |
|---|---|
| forNormal | 1910309 |
| forUnckecked | 570287 ✅ |
Testing
forge test --contracts 05_uint/Uint.T.sol --gas-report
Gas report
| Function Name | Gas Cost |
|---|---|
| read Uint8 | 2379 |
| read Uint128 | 2465 |
| read Uint256 | 2317 ✅ |
| set Uint8 | 5355 |
| set Uint128 | 5358 |
| set Uint256 | 5322 ✅ |
Testing
forge test --contracts 06_Error/Error.T.sol --gas-report
Gas report
| Error Name | Gas Cost |
|---|---|
| Assert | 180 |
| Require | 268 |
| Revert | 164 ✅ |
Testing
forge test --contracts 07_LocalData/LocalData.T.sol --gas-reportGas report
| Data Type | Gas Cost |
|---|---|
| localData | 1902339 ✅ |
| storageData | 4022155 |
Testing
forge test --contracts 08_Clone2/Clone2.T.sol --gas-reportGas report
| Create Type | Gas Cost |
|---|---|
| clone2 | 41493 ✅ |
| create2 | 93031 |
| new | 79515 |
Testing
forge test --contracts 09_Packing/Packing.T.sol --gas-reportGas report
| Create Type | Gas Cost |
|---|---|
| normal | 133521 |
| packing | 111351 ✅ |
forge test --contracts 10_Increment/Increment.T.sol --gas-reportGas report
| Increment | Gas Cost |
|---|---|
| i += 1 | 270 |
| i = i +1 | 248 |
| i++ | 220 |
| ++i | 193 ✅ |
Testing
forge test --contracts 11_ReentrancyGuard/ReentrancyGuard.T.sol --gas-reportGas report
| ReentrancyGuard | Gas Cost | tips |
|---|---|---|
| Bool | 69395 | |
| Uint01 | 69354 | 0 to non-zero -> 20000 gas |
| Uint12 | 89259 ✅ | non-zero to non-zero -> 2900 gas |