Skip to content

Is the max function written in assembly gas optimized #1444

Open
@XuHugo

Description

@XuHugo

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 |
╰----------------------------------+-----------------+-----+--------+-----+---------╯

`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions