Skip to content

Commit

Permalink
Refs Conflux-Chain#454 -- Added LocalVeriables to general/build/smart…
Browse files Browse the repository at this point in the history
…-contracts/gas-optimization
  • Loading branch information
jackleeio committed Mar 24, 2024
1 parent 935e36e commit 5c05e07
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
---
displayed_sidebar: generalSidebar
---
# Constant vs Immutable

1. `constant`: Declares a constant that must be initialized at the time of declaration and cannot be altered thereafter.
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 5c05e07

Please sign in to comment.