FreshCryptoLib icon indicating copy to clipboard operation
FreshCryptoLib copied to clipboard

Optimize Skipping of 0-bits In mulmuladd

Open nlordell opened this issue 1 year ago • 3 comments
trafficstars

When investigating the mulmuladd issue, I noticed that at the start of the function, we have a loop to skip index for leading 0s in both u and v.

Currently, it was computing the a value 0bXY (where X bit being set indicates that v{index} is set, and Y bit indicates that u{index} is set) and storing it to a temporary variable (T4) for checking if the leading bit was 0 or not. This PR changes the logic to store it directly to the zz variable instead of having it be recomputed after the loop finishes.

At first, this was implemented by changing the condition of the loop to "is either v{index} or u{index} set?" but computing zz directly should be slightly better on average (if we assume even bit distribution, there is only a 25% chance this will save gas).

Also, eq(X, 0) -> iszero(X) for slightly smaller code and less gas used.

What is the best way to benchmark the difference?

nlordell avatar Dec 15 '23 09:12 nlordell

What is the best way to benchmark the difference?

Not sure about the project's benchmarking conventions, but perhaps you can run the tests with the --gas-report flag. More on it here: https://book.getfoundry.sh/forge/gas-reports

mmv08 avatar Dec 15 '23 10:12 mmv08

Could you ensure linting and rebase with previous PR to ensure CI's OK?

For the rest OK for me.

rdubois-crypto avatar Dec 18 '23 11:12 rdubois-crypto

@rdubois-crypto - should be rebased to latest master.

nlordell avatar Jan 15 '24 14:01 nlordell