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

Loop gas usage optimization #16

Closed
YouStillAlive opened this issue Mar 28, 2024 · 0 comments · Fixed by #19
Closed

Loop gas usage optimization #16

YouStillAlive opened this issue Mar 28, 2024 · 0 comments · Fixed by #19
Assignees
Labels

Comments

@YouStillAlive
Copy link
Member

Risk Level
Severity: Gas

Code Segment

function _concatParams(
        uint amount,
        uint256[] calldata params
    ) internal pure returns (uint256[] memory result) {
        uint256 length = params.length;
        result = new uint256[](length + 1);
        result[0] = amount;
        for (uint256 i = 0; i < length; ) {
            result[i + 1] = params[i];
            unchecked {
                ++i;
            }
        }
    }

Description
It was identified that the for loops employed in the contracts can be gas
optimized by the following principles:
• Unnecessary reading of the array length on each iteration wastes gas.
• Loop counters do not need to be set to 0, since uint256 is already initialized to 0.
• It is also possible to further optimize loops by using unchecked loop index incrementing
and decrementing.

Recommendation
Consider changing to:

for (uint256 i; i < length; ) {
            result[i + 1] = params[i];
            unchecked {
                ++i;
            }
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant