5

This is the multiplication method from the SafeMath library.

/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal 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;
}

Could this be done using the shift operators in Solidity to reduce the amount of gas consumed?

enter image description here

If yes, what would the necessary changes look like?

6
  • yeah, it is a standard way to divide numbers in all languages starting from Solidity and ending with C, but the only problem is that shifts only divide by multiples of 2
    – Nulik
    Feb 1, 2021 at 20:32
  • what i wanna do is make it cheaper. how about this --> medium.com/wicketh/mathemagic-full-multiply-27650fec525d Feb 1, 2021 at 20:39
  • and how much are you gonna save on math operations? these are not expensive. I would go for SSTORE, it is spending around 20k Gas. If you pack many variables into single SSTORE operation you are going to save by 20k gas on each SSTORE
    – Nulik
    Feb 1, 2021 at 20:44
  • how can i exactly calulate the difference in gas between this safemath operation and the one from that medium article Feb 1, 2021 at 20:49
  • @smatthewenglish the easiest way to compare gas costs across different contracts is to use Remix by pasting the contracts in there and monitoring the gas reported in the logs at the bottom of the page. Apr 12, 2021 at 7:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.