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

Prefix increments are cheaper than postfix increments #18

Open
code423n4 opened this issue Dec 9, 2021 · 1 comment
Open

Prefix increments are cheaper than postfix increments #18

code423n4 opened this issue Dec 9, 2021 · 1 comment
Assignees
Labels
bug Something isn't working G (Gas Optimization) sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons

Comments

@code423n4
Copy link
Contributor

Handle

robee

Vulnerability details

Prefix increments are cheaper than postfix increments.
Further more, using unchecked {++x} is even more gas efficient, and the gas saving accumulates every iteration and can make a real change
There is no risk of overflow caused by increamenting the iteration index in for loops (the ++i in for (uint256 i = 0; i < numIterations; ++i)).
But increments perform overflow checks that are not necessary in this case.
These functions use not using prefix increments (++x) or not using the unchecked keyword:

    change to prefix increment and unchecked: TwabRewards.sol, index, 172
    change to prefix increment and unchecked: TwabRewards.sol, index, 217
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Dec 9, 2021
code423n4 added a commit that referenced this issue Dec 9, 2021
@PierrickGT PierrickGT added the sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons label Dec 10, 2021
@PierrickGT
Copy link
Member

I did some gas golfing to figure out if ++i is really less gas consuming than i++. We would only save 5 gas per iteration but also lose in code clarity, so this gas saving trade off isn't really worth it.

About the unchecked part, results are a bit more convincing but still negligible. We would save 77 gas per iteration but as stated in the following issue, it is not possible to write unchecked { ++i } inline so we would have to write a helper function which would make our code less legible and harder to maintain in the future.

ethereum/solidity#10695

I've acknowledged the issue but we won't actually make the changes cause we prefer to keep a simple code base that will be easier to maintain in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working G (Gas Optimization) sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons
Projects
None yet
Development

No branches or pull requests

2 participants