Skip to content
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

Reduces mul execution cost #95

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

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