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

6 stars 4 forks source link

Gas Optimizations #166

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

[S]: Suggested optimation, save a decent amount of gas without compromising readability;

[M]: Minor optimation, the amount of gas saved is minor, change when you see fit;

[N]: Non-preferred, the amount of gas saved is at cost of readability, only apply when gas saving is a top priority.

[M] ++i is more efficient than i++

Using ++i is more gas efficient than i++, especially in a loop.

For example:

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/DexManagerFacet.sol#L33-L33

        for (uint256 i; i < _dexs.length; i++) {

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/DexManagerFacet.sol#L52-L52

        for (uint256 i; i < s.dexs.length; i++) {

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/DexManagerFacet.sol#L65-L76

        for (uint256 i; i < _dexs.length; i++) {
            if (s.dexWhitelist[_dexs[i]] == false) {
                continue;
            }
            s.dexWhitelist[_dexs[i]] = false;
            for (uint256 j; j < s.dexs.length; j++) {
                if (s.dexs[j] == _dexs[i]) {
                    _removeDex(j);
                    return;
                }
            }
        }

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/DiamondLoupeFacet.sol#L24-L24

        for (uint256 i; i < numFacets; i++) {

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/HopFacet.sol#L48-L48

        for (uint8 i; i < _tokens.length; i++) {

https://github.com/code-423n4/2022-03-Li.finance/blob/699c2305fcfb6fe8862b75b26d1d8a2f46a551e6/src/Facets/Swapper.sol#L14-L14

        for (uint8 i; i < _swapData.length; i++) {

[S] Cache array length in for loops can save gas

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Instances include:

        for (uint8 i; i < _swapData.length; i++) 
H3xept commented 2 years ago

Re Cache array length in for loops can save gas

Duplicate of #44

H3xept commented 2 years ago

Re prefix increments

We internally decided to avoid previx increments for now.