Gas Optimizations #70
Labels
bug
Something isn't working
G (Gas Optimization)
sponsor confirmed
Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
Gas optimizations
Use delete in the
claimRewards
function of theFlywheelCore
contract and in the_decrementVotesUntilFree
function of theERC20MultiVotes
contract in order to trigger a gas refundLoops can be optimized in several ways. Let's take for example the loop in the
incrementGauges
function inERC20Gauges
(There is also a loop in thedecrementGauges
function which is similar).We can do multiple things here:
uint i;
instead ofuint i = 0;
.Let's look at another example:
First of all, the optimizations from the loop before can be done here too. In addition, there is another optimization that can be done here - the condition of the loop contains 2 conditions -
i < size && (userFreeWeight + totalFreed) < weight
.In order to avoid calculating
userFreeWeight + totalFreed
in every iteration, you can calculateweight - userFreeWeight
(let's assume thatweightLeftToFree == weight - userFreeWeight
) once and change the condition tototalFreed < weightLeftToFree
. You can also use unchecked on the calculation ofweightLeftToFree
because you know for sure thatweight > userFreeWeight
(or there was no weight to free).Use unchecked in
_incrementDelegation
and_undelegate
inERC20MultiVotes
In the
_incrementDelegation
function you increment both_delegatesVotesCount[delegator][delegatee]
anduserDelegatedVotes[delegator]
. We know for sure that_delegatesVotesCount[delegator][delegatee] <= userDelegatedVotes[delegator]
, becauseuserDelegatedVotes[delegator]
is incremented at least any time that_delegatesVotesCount[delegator][delegatee]
(it's also incremented when delegating other delegatees), so unchecked can be used when incrementing_delegatesVotesCount[delegator][delegatee]
because if it will overflowuserDelegatedVotes[delegator]
will overflow too.We can see a similar thing in the
_undelegate
function. In that function we decrement both_delegatesVotesCount[delegator][delegatee]
anduserDelegatedVotes[delegator]
, and for the same reason we know that ifuserDelegatedVotes[delegator]
will underflow,_delegatesVotesCount[delegator][delegatee]
will underflow too, so we can use unchecked when decrementinguserDelegatedVotes[delegator]
.The text was updated successfully, but these errors were encountered: