Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas Optimizations #251

Open
code423n4 opened this issue May 24, 2022 · 0 comments
Open

Gas Optimizations #251

code423n4 opened this issue May 24, 2022 · 0 comments
Labels
bug Something isn't working duplicate This issue or pull request already exists G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

++i is cheaper than i++

Use prefix increment instead of postfix increment.

Unnecessary checked arithmetic in for loops

The i++ part of for loops can be surrounded by the unchecked keyword to save gas. For example:

for (uint256 i = 0; i < 10; i++) {
...
}

can be optimized to:

for (uint256 i = 0; i < 10;) {
...
unchecked { i++; }
}

!= 0 is cheaper than > 0 (unsigned integers)

When dealing with unsigned integers the != 0 comparison is equivalent to > 0 comparison. It is also cheaper, therefore you should use it instead.

Cache Array Length Outside of Loop

You can optimize for loops that iterate over array elements by caching the array length in a local variable. This will reduce the number of MLOADs and will save gas. For example:

for (uint256 i = 0; i < array.length; i++) {
...
}

can be optimized to:

uint256 length = array.length;
for (uint256 i = 0; i < length; i++) {
...
}

Repeated computation of the same value in AuraLocker._processExpiredLocks()

That function computes length - 1 multiple times. The result can be computed once and be cached in a local variable in order to save gas.

Repeated access to the current array element in for loops

Many for loops that iterate over array elements access the current element (array[i]) more than once in each iteration. This element can be accessed only once (and be cached in a local variable) in order to avoid the additional array-boundaries check that Solidity performs with each array access, and save gas.

@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels May 24, 2022
code423n4 added a commit that referenced this issue May 24, 2022
@0xMaharishi 0xMaharishi added the duplicate This issue or pull request already exists label May 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working duplicate This issue or pull request already exists G (Gas Optimization)
Projects
None yet
Development

No branches or pull requests

2 participants