kasoqian

kasoqian

区块链步道师,传播区块链技术

WTF Gas Optimization

WTF Gas Optimization#

Solidity gas optimization techniques, using Foundry. 总结写 Solidity 智能合约更省 gas 的技巧。

大纲#

1. use constant and immutable

2. use calldata over memory

3. use Bitmap

4. use unchecked

5. use uint256 over uint8

6. use custom error over require/assert

7. use local variable over storage

8. use clone2 over new/create2

9. packing storage slots

1. use constant and immutable#

Code | 文章

Testing

forge test --contracts 01_Constant/Constant.t.sol --gas-report

Gas report

Function NameGas Cost
varConstant183
varImmutable161 ✅
variable2305

2. use calldata over memory#

Code | 文章

Testing

forge test --contracts 02_CalldataAndMemory/CalldataAndMemory.T.sol --gas-report

Gas report

Function NameGas Cost
writeByCalldata67905 ✅
writeByMemory68456

3. use Bitmap#

Code | 文章

Testing

forge test --contracts 03_Bitmap/Bitmap.T.sol --gas-report

Gas report

Function NameGas Cost
setDataWithBitmap22366 ✅
setDataWithBoolArray35729

4. use unchecked#

Code | 文章

Testing

forge test --contracts 04_unchecked/Unchecked.T.sol --gas-report

Gas report

Function NameGas Cost
forNormal1910309
forUnckecked570287 ✅

5. use uint256 over uint8#

Code | 文章

Testing

forge test --contracts 05_uint/Uint.T.sol --gas-report

Gas report

Function NameGas Cost
read Uint82379
read Uint1282465
read Uint2562317 ✅
set Uint85355
set Uint1285358
set Uint2565322 ✅

6. use custom error over require/assert#

Code | 文章

Testing

forge test --contracts 06_Error/Error.T.sol --gas-report

Gas report

Error NameGas Cost
Assert180
Require268
Revert164 ✅

7. use local variable over storage#

Code | 文章

Testing

forge test --contracts 07_LocalData/LocalData.T.sol --gas-report

Gas report

Data TypeGas Cost
localData1902339 ✅
storageData4022155

8. use clone2 over new/create2#

Code | 文章

Testing

forge test --contracts 08_Clone2/Clone2.T.sol --gas-report

Gas report

Create TypeGas Cost
clone241493 ✅
create293031
new79515

9. packing storage slots#

Code

Testing

forge test --contracts 09_Packing/Packing.T.sol --gas-report

Gas report

Create TypeGas Cost
normal133521
packing111351 ✅

WTF Gas Optimization 贡献者#

贡献者是WTF学院的基石 #

image
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.