Description
I used src/utils/FixedPointMathLib.sol for testing and found that the gas consumption of the max function was not as low as that of the ternary operation.Could you help me clear up my doubts.
Tool:
foundry
Code:
`
function soliditymax(uint256 x, uint256 y) public pure returns (uint256 z) {
z = x > y ? x : y;
}
function assemblymax(uint256 x, uint256 y) public pure returns (uint256 z) {
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
`
Test result:
`
╭----------------------------------+-----------------+-----+--------+-----+---------╮
| src/MathOpt.sol:MathOpt Contract | | | | | |
+===================================================================================+
| Deployment Cost | Deployment Size | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| 182156 | 581 | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| | | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| Function Name | Min | Avg | Median | Max | # Calls |
|----------------------------------+-----------------+-----+--------+-----+---------|
| assemblymax | 790 | 790 | 790 | 790 | 1 |
╰----------------------------------+-----------------+-----+--------+-----+---------╯
╭----------------------------------+-----------------+-----+--------+-----+---------╮
| src/MathOpt.sol:MathOpt Contract | | | | | |
+===================================================================================+
| Deployment Cost | Deployment Size | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| 182156 | 581 | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| | | | | | |
|----------------------------------+-----------------+-----+--------+-----+---------|
| Function Name | Min | Avg | Median | Max | # Calls |
|----------------------------------+-----------------+-----+--------+-----+---------|
| soliditymax | 776 | 776 | 776 | 776 | 1 |
╰----------------------------------+-----------------+-----+--------+-----+---------╯
`