Gas Optimizations #135
Labels
bug
Something isn't working
G (Gas Optimization)
sponsor confirmed
Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
valid
Gas Optimizations
The following sections detail the gas optimizations found throughout the codebase. Each optimization is documented with the setup, an explainer for the optimization, a gas report and line identifiers for each optimization across the codebase. For each section's gas report, the optimizer was turned on and set to 10000 runs. You can replicate any tests/gas reports by heading to 0xKitsune/gas-lab and cloning the repo. Then, simply copy/paste the contract examples from any section and run
forge test --gas-report
. You can also easily update the optimizer runs in thefoundry.toml
.Use assembly to write storage values
Gas Report
Lines
MyStrategy.sol:71
MyStrategy.sol:88
MyStrategy.sol:94
MyStrategy.sol:310
MyStrategy.sol:312
Use assembly when getting a contract's balance of ETH.
You can use
selfbalance()
instead ofaddress(this).balance
when getting your contract's balance of ETH to save gas. Additionally, you can usebalance(address)
instead ofaddress.balance()
when getting an external contract's balance of ETH.Gas Report
Lines
MyStrategy.sol:303
MyStrategy.sol:322
unchecked{++i}
instead ofi++
(or use assembly when applicable)Use
++i
instead ofi++
. This is especially useful in for loops but this optimization can be used anywhere in your code. You can also useunchecked{++i;}
for even more gas savings but this will not check to see ifi
overflows. For extra safety if you are worried about this, you can add a require statement after the loop checking ifi
is equal to the final incremented value. For best gas savings, use inline assembly, however this limits the functionality you can achieve. For example you cant use Solidity syntax to internally call your own contract within an assembly block and external calls must be done with thecall()
ordelegatecall()
instruction. However when applicable, inline assembly will save much more gas.Gas Report
Lines
MyStrategy.sol:118
MyStrategy.sol:153
MyStrategy.sol:300
MyStrategy.sol:317
Use multiple
require()
statments insted ofrequire(expression && expression && ...)
Gas Report
Lines
Use assembly to check for address(0)
Gas Report
Lines
The text was updated successfully, but these errors were encountered: