Skip to content

Commit

Permalink
Refs #454 -- Added LocalVeriables to general/build/smart-contracts/ga…
Browse files Browse the repository at this point in the history
…s-optimization (#481)
  • Loading branch information
jackleeio authored Mar 28, 2024
1 parent 5a3feb0 commit 02bd78a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
---
displayed_sidebar: generalSidebar
sidebar_position: 1

---

Expand Down
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.

0 comments on commit 02bd78a

Please sign in to comment.