-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refs #454 -- Added LocalVeriables to general/build/smart-contracts/ga…
…s-optimization (#481)
- Loading branch information
Showing
2 changed files
with
36 additions
and
1 deletion.
There are no files selected for viewing
1 change: 0 additions & 1 deletion
1
docs/general/build/smart-contracts/gas-optimization/constant.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,5 @@ | ||
--- | ||
displayed_sidebar: generalSidebar | ||
sidebar_position: 1 | ||
|
||
--- | ||
|
||
|
36 changes: 36 additions & 0 deletions
36
docs/general/build/smart-contracts/gas-optimization/local-variables.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
--- | ||
displayed_sidebar: generalSidebar | ||
--- | ||
# Local Variables | ||
|
||
In many common DeFi projects, we frequently encounter various complex calculations that inevitably require defining many new local variables and updating existing global variables. It's well-known that modifying storage is significantly more expensive than making changes in memory. | ||
|
||
**Demo Code** | ||
|
||
Below, we present two different methods to modify storage variables and observe the gas difference. | ||
|
||
```solidity | ||
contract LocalVariablesExample { | ||
uint globalCounter; | ||
// gas: 4022155 | ||
function modifyStorageDirectly(uint iterations) external { | ||
for (uint i = 0; i < iterations; i++) { | ||
globalCounter++; | ||
} | ||
} | ||
// gas: 1902339 | ||
function modifyUsingLocalVariable(uint iterations) external { | ||
uint localCounter = 0; | ||
for (uint i = 0; i < iterations; i++) { | ||
localCounter++; | ||
} | ||
globalCounter = localCounter; | ||
} | ||
} | ||
``` | ||
|
||
Recommendations for gas optimization: | ||
|
||
🌟 For complex calculations, bypass direct storage variable manipulation to save on high gas costs. Instead, use local variables for interim modifications, then update storage variables in one go. This approach significantly reduces gas usage. |