You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When the total reported amount of assets is estimated by the actions, the storage variable actions.length is used. This value does not change over time (in this loop) and can be cached in a local variable, instead of retrieving the value from the storage.
Cache the length locally and use the local variable in the loop.
Reference
An example was created to illustrate the gas difference with or without length cache.
Not using a cache, for a set of 10 iterations uses 49157 gas.
contractSumNumbers {
uint[] public numbers;
constructor(uintsize) {
// Add some data to work withfor (uint i =0; i < size; i++) {
numbers.push(i);
}
}
function sumNumbers() publicviewreturns (uint) {
uint sum;
for(uint i =0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
}
Using a cache, for the same set of 10 iterations uses 48168 gas.
contractSumNumbersWithCache {
uint[] public numbers;
constructor(uintsize) {
// Add some data to work withfor (uint i =0; i < size; i++) {
numbers.push(i);
}
}
function sumNumbers() publicviewreturns (uint) {
uint sum;
uint size = numbers.length;
for(uint i =0; i < size; i++) {
sum += numbers[i];
}
return sum;
}
}
Both contracts were compiled with 200 optimization rounds.
The text was updated successfully, but these errors were encountered:
Description
When the total reported amount of assets is estimated by the actions, the storage variable
actions.length
is used. This value does not change over time (in this loop) and can be cached in a local variable, instead of retrieving the value from the storage.https://github.com/monoceros-alpha/review-opyn-perp-vault-templates-2021-07/blob/518e4f6d174cae6ee75e316ad56789aaeb695069/code/contracts/core/OpynPerpVault.sol#L393-L395
Similarly for
_closeAndWithdraw()
:https://github.com/monoceros-alpha/review-opyn-perp-vault-templates-2021-07/blob/3d44603300dd9abffe5a1c1e1c2647e9f6b80c7b/code/contracts/core/OpynPerpVault.sol#L420
Recommendation
Cache the length locally and use the local variable in the loop.
Reference
An example was created to illustrate the gas difference with or without length cache.
Not using a cache, for a set of 10 iterations uses 49157 gas.
Using a cache, for the same set of 10 iterations uses 48168 gas.
Both contracts were compiled with 200 optimization rounds.
The text was updated successfully, but these errors were encountered: