-
Notifications
You must be signed in to change notification settings - Fork 11.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Optimize log2
with a lookup table
#5236
Optimize log2
with a lookup table
#5236
Conversation
|
@Lohann could you take a look at Lohann#1? cross sharing:
|
Great work @cairoeth ! your solution is cleaner, cheaper and generates a smaller binary, will update this PR with your proposal. |
Use single lookup and binary search for log2
log2
with a lookup table
23% more efficient Log2 method
Follow an efficient implementation of
floor(log2(x))
which uses ~23% less gas than the current implementation.log2
is quite central for many other math operations, such as:sqrt
uses log2 internally (even so the currentsqrt
uses an specialized log2 implementation).255 - log2(value) + toUint(value == 0)
This implementation uses lookup tables to calculate
floor(log2(x))
using218 gas
, which is65 gas
units less than the current implementation.Obs: the code in this PR have a more detailed documentation on how the algorithm works:
Lookup tables are quite powerful and should be explored more in Solidity, I use it in another project for validate 6 different method
selectors
in constant gas, using less than100 gas
units, way smaller and more efficient than the nested ifs or binary search generated by default by the Solidity Compiler:https://github.com/Lohann/universal-factory/blob/e6e3e6acc3f3b8a9bf0d1495c0f8fdb47d88a801/src/UniversalFactory.sol#L305-L346
PR Checklist
npx changeset add
)