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
After the (welcomed) introduction of the checked math operators in solidity 0.8.x, developers can allow safe unchecked operations by wrapping them in a unchecked {} block. Safety checks of course apply to pre and post increment/decrement operators (++/--) which are commonly used to increase indexes in for loops; unfortunately the safety checks in this case are enabled by default, and there is no way of disabling it in a developer friendly way. This may force to refactor the for loop in a while, or change the for increment in an unnatural way. Not doing it can get (very) expensive.
Motivation
Loops are in most cases bounded by definition (the bounding is represented by the exit condition). Therefore in the vast majority of cases, checking for overflows is really not needed, and can get very gas expensive. Consider the following examples:
pragma solidity ^0.8.0;
contract Test1 {
function loop() public pure {
for(uint256 i = 0; i < 100; i++) {
}
}
}
pragma solidity ^0.8.0;
contract Test {
function loop() public pure {
for(uint256 i = 0; i < 100;) {
unchecked {
i++;
}
}
}
}
loop() in Test1 costs more than 31K gas, vs 25.5K gas for loop() in Test2
Specification
allow to specify unchecked increments in for loops as follows
for(uint256 i = 0; i < 100; unchecked i++)
The text was updated successfully, but these errors were encountered:
Abstract
After the (welcomed) introduction of the checked math operators in solidity 0.8.x, developers can allow safe unchecked operations by wrapping them in a
unchecked {}
block. Safety checks of course apply to pre and post increment/decrement operators (++/--) which are commonly used to increase indexes in for loops; unfortunately the safety checks in this case are enabled by default, and there is no way of disabling it in a developer friendly way. This may force to refactor the for loop in a while, or change the for increment in an unnatural way. Not doing it can get (very) expensive.Motivation
Loops are in most cases bounded by definition (the bounding is represented by the exit condition). Therefore in the vast majority of cases, checking for overflows is really not needed, and can get very gas expensive. Consider the following examples:
loop()
in Test1 costs more than 31K gas, vs 25.5K gas forloop()
in Test2Specification
allow to specify unchecked increments in for loops as follows
for(uint256 i = 0; i < 100; unchecked i++)
The text was updated successfully, but these errors were encountered: