Skip to content

Conversation

@0xtotem
Copy link

@0xtotem 0xtotem commented Jan 14, 2023

This is a minor PR that reduces mul execution cost from 21769 down to 21748 when a != 0.

This PR recommends to add the a == 0 test on top of the function but it turns out that with Solidity ^0.6.12 this isn't true.

Code use for testing:

pragma solidity ^0.6.12;

contract SafeMath {
    function mul(uint256 a, uint256 b) public pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");

        return c;
    }

    function mul2(uint256 a, uint256 b) public pure returns (uint256) {
        uint256 c = a * b;
        require(a == 0 || c / a == b, "SafeMath: multiplication overflow");

        return c;
    }
}

Reduces from 21769 down to 21748 when a != 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant