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

Slight for loop gas optimization #5

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

redsh4de
Copy link

  • Changed increment operations to use pre-increment instead of post-increment to save an extra operation
  • for loop iterator incrementing is moved into an unchecked block to skip overflow checks and save gas - given that i has a maximum limit set by the loop, there are no downsides for this approach

Use unchecked and pre-increment for for-loop iterators
@@ -102,7 +103,8 @@ library LibDiamond {
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
++selectorPosition;
unchecked { ++selectorIndex; }
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++)

selectorPosition is now being incremented twice in each iteration of the loop, instead of once.

@mudgen
Copy link
Owner

mudgen commented Sep 17, 2023

@redsh4de I appreciate this. I found one bug in the pull request. Please fix and I can merge. Thanks for your help.

… for loop

Remove selectorIndex++ from the for loop, as incrementing is being done in an unchecked block already
@redsh4de
Copy link
Author

redsh4de commented Sep 17, 2023

That should take care of it! @mudgen

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants