0

Any ideas if I can optimize the gas of the following function from Math library of OZ:

function max(uint256 a, uint256 b) public pure returns (uint256) {
    return a >= b ? a : b;
}

*I checked all possible gas optimization patterns but still no answer. Personally, it is already as optimized as possible.

1 Answer 1

0

Just playing around, but it seems that this version is slightly more gas efficient :

function max(uint256 a, uint256 b) public pure returns (uint256 result) {
   assembly {
     let tmp := gt(a, b)
     result := add(mul(tmp, a), mul(sub(1, tmp), b))
   }
}

Which basically reworks the branches into a single arithmetic expression. Your original ternary version uses 21666 gas (a > b) or 21676 gas (b > a) on default settings, giving an average gas cost of 21671, while this one uses a constant 21645 gas.

The improvement is marginal at best and doesn't justify the loss of readability of assembly in my opinion...

6
  • you meant to use Yul. can you do the same but for a minimum function like this? return a < b ? a : b;
    – Decode_me
    May 24 at 11:18
  • I don't understand your comment ? the assembly block is just another way to write return a < b ? a: b;
    – hroussille
    May 24 at 12:19
  • I meant how to transform it into assembly code
    – Decode_me
    May 24 at 13:05
  • This is already inline assembly.. You can replace your function with the one I proposed. It's all valid solidity.
    – hroussille
    May 24 at 13:43
  • I talked about this part: return a < b ? a: b; To code in assembly
    – Decode_me
    May 24 at 17:56

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.