Skip to content

Conversation

@z0r0z
Copy link
Contributor

@z0r0z z0r0z commented Jan 2, 2024

Description

Not totally sure why but this seems to save some gas in loops (!=).

Checklist

Ensure you completed all of the steps below before submitting your pull request:

  • Ran forge snapshot?
  • Ran npm run lint?
  • Ran forge test?

Pull requests with an incomplete checklist will be thrown out.

// the array index counter which cannot possibly overflow.
unchecked {
for (uint256 i = 0; i < owners.length; ++i) {
for (uint256 i = 0; i != owners.length; ++i) {
Copy link
Contributor

@sambacha sambacha Jul 6, 2025

Choose a reason for hiding this comment

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

         unchecked {
-            for (uint256 i = 0; i < owners.length; ++i) {
+            uint256 len = owners.length;
+            for (uint256 i = 0; i < len; ++i) {
                 balances[i] = balanceOf[owners[i]][ids[i]];
             }
         }


// Storing these outside the loop saves ~15 gas per iteration.
uint256 id;
uint256 amount;
Copy link
Contributor

Choose a reason for hiding this comment

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

         // Storing these outside the loop saves ~15 gas per iteration.
         uint256 id;
         uint256 amount;
+        uint256 len = ids.length;
 
-        for (uint256 i = 0; i < ids.length; ) {
+        for (uint256 i = 0; i < len; ) {
             id = ids[i];
             amount = amounts[i];

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