-
Notifications
You must be signed in to change notification settings - Fork 11.8k
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
The SafeMath.div
function needlessly allocates memory
#2413
Comments
Hi @nlordell ! Thanks for the suggestion, it is really appreciated. The project owner will review your suggestion as soon as they can. Please wait until we have discussed this idea before writing any code or submitting a Pull Request, so we can go through the design beforehand. We don’t want you to waste your time! |
The same scenario can be reproduced for
|
Thanks everyone for reporting and testing this. I am very interested in these results and will be looking into it. |
FIxes OpenZeppelin#2413, remove the string allocation in SafeMath default functions: caused unrecovered memory allocation even for successfull calls
Note; Fix requiers some code duplication, to make sure that these defaults function do not allocate string unless they are just about to revert. PR #2462 fixes that issue, as shown by the tests. I also used the occasion to add "custom revert message" versions of |
The
SafeMath.div
function needlessly allocates memory.💻 Environment
All environments.
📝 Details
Calling
SafeMath.div(uint256, uint256)
allocates memory in order to pass a revert reason toSafeMath.div(uint256, uint256, string memory)
, even if the operation would not revert. This causes an addition 64-byte allocation per call for the revert reason stringlength || paddedContents
.While in it of itself, this is a minor issue, it is worth noting that the other
SafeMath
methods do not have the same problem, and that in a loop, the gas cost ofSafeMath.div
grows quadratically (because of memory costs) instead of linearly with the number of iterations as one would naturally expect.🔢 Code to reproduce bug
The easiest way to reproduce this is to use the following code in Remix and calling
doThings
with varying lengths ofthings
input:The call to
doThing
allocates 64 bytes per call, because of thediv
call. Replacingthing.div(2)
withthing / 2
reduces memory allocation to 0 as expected.The text was updated successfully, but these errors were encountered: