code-423n4 / 2021-10-tempus-findings

0 stars 0 forks source link

Cache array length in for loops can save gas #31

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

WatchPug

Vulnerability details

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:

https://github.com/code-423n4/2021-10-tempus/blob/63f7639aad08f2bba717830ed81e0649f7fc23ee/contracts/amm/VecMath.sol#L14-L16

function sub(uint256[] memory vec1, uint256[] memory vec2) internal pure {
        assert(vec1.length == vec2.length);
        for (uint256 i = 0; i < vec1.length; ++i) {
mijovic commented 2 years ago

This will mostly be executed on small arrays. This gas saving is irrelevant to gas usage for any of the protocol functions. Also, compiler might be able to optimize out this, so I would not fix this, as in general code will be less readable for saving of 20 gas maximum ...