code-423n4 / 2022-03-joyn-findings

4 stars 1 forks source link

Gas Optimizations #94

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

JOYN Contest

April 1, 2022

@securerodd #

Gas Optimizations

1. For Loop Improvements through Local Variable Caching and Prefix Increment

The for loop in createProject(string memory _projectId, Collection[] memory _collections) within CoreFactory.sol performs a length check and postfix increment at each iteration. The code can be seen below:

require(
    _collections.length > 0,
    'CoreFactory: should have more at least one collection'
);

    for (uint256 i; i < _collections.length; i++) {
    ...
    }

This can be improved by storing the collections length in a local variable in memory and using a prefix increment instead.

Recommended logic:

uint collLength = _collections.length;
require(
    collLength > 0,
    'CoreFactory: should have more at least one collection'
);

    for (uint256 i; i < collLength; ++i) {
    ...
    }

Output of provided tests can be seen below. The gas savings would be greater for projects with larger collections.

Existing logic:

__________________________________________________________________________________________________
| Contract          ·  Method              ·  Min        ·  Max        ·  Avg         ·  # calls |    
__________________________________________________________________________________________________
| CoreFactory       ·  createProject       ·  463683     ·  878840     ·  602069      ·     6    |
__________________________________________________________________________________________________

Recommened logic:

__________________________________________________________________________________________________
| Contract          ·  Method              ·  Min        ·  Max        ·  Avg         ·  # calls |    
__________________________________________________________________________________________________
| CoreFactory       ·  createProject       ·  463671     ·  878820     ·  602054      ·     6    |
__________________________________________________________________________________________________