Instead of updating struct fields individually by reading the struct each time from memory, its better to create the updated struct in memory the write it to storage once.
Consider the following snippet from Lender.buyLoan()
:
In order to update the loan variable, there are 7 reads being performed from the storage. We can save on a lot of gas by first creating the updated loan struct, then overwriting the old one with it:
With this simple change, major gas saving of 99630
and 99238
gas were observed in the test_buyLoan()
and test_giveLoan()
tests respectively, totalling a total gas saving of 198868
gas. The same optimization could be applied to other places where many storage reads are made.
Gas
Foundry, Forge
Perform updates in memory, then write to storage at once.
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.