0

According to the EVM Gas Cost Yellow Paper (can be found here):

  • The cost of % is 5
  • The cost of & is 3

When x is a power of 2, the expression a % x is equivalent to a & (x - 1).

If x is a constant variable, then this replacement can take place during compilation.

Can I trust the Solidity compiler to do this when optimization is enabled?

I am currently using solcjs, but the same question goes for truffle, Remix IDE, etc.

Thank you!!!

| improve this question | | | | |
1

From a quick test on Remix, it looks like enabling optimization does not get rid of the MOD opcode in the following code, so I believe the answer is "No, you cannot trust solc to perform this optimization."

contract Test {
    function test(uint256 x) public pure returns (uint256) {
        return x % 4;
    }
}
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.