-
Notifications
You must be signed in to change notification settings - Fork 11.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Loop gas optimisation #5028
Comments
CarsonCase
added a commit
to CarsonCase/openzeppelin-contracts
that referenced
this issue
May 9, 2024
CarsonCase
added a commit
to CarsonCase/openzeppelin-contracts
that referenced
this issue
May 9, 2024
3 tasks
You are pointing out the right thing @FlyingStraus. There are a lot of projects with the same unoptimized code as per my knowledge. Accessing the length of some storage datatype again and again in a for loop is often more costly than keeping that same specific length in some particular |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The MerkleProof.sol contract by OZ is used very widely in contracts for EVM chains. Some of the functions are used for-loop. And the way that this for-loop is not the gas-optimal
📝 Details
After the gas optimized code will consume 100 gas units less per each element of an array.
🔢 Code to reproduce bug
The overheads outlined below are PER LOOP, excluding the first loop
storage arrays incur a Gwarmaccess (100 gas) memory arrays use MLOAD (3 gas) calldata arrays use CALLDATALOAD (3 gas) Caching the length changes each of these to a DUP (3 gas), and gets rid of the extra DUP needed to store the stack offset
As you see on a screenshot, the difference between these two calls is around 10_000 gas units, for a array length of a 100 elements.
Which is not pretty much for one call, But since a lot of contracts use this OZ library, the total amount of overspent gas is high.
Code snippet:
openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
Line 64 in c80b675
openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
Line 53 in c80b675
Recomendation
And Recommendation is to calculate the length of an array one's and keep it locally
The text was updated successfully, but these errors were encountered: