-
Notifications
You must be signed in to change notification settings - Fork 105
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
feat: fast const pow #336
feat: fast const pow #336
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see some places where pow is used pow(2, ...)
could you also update those?
Same for pow(10, ...)
I can do it but I am not sure it makes sense because pow(2, ...) uses a generic, so it returns T. If I try to replace its usages by pow2 I will usually have to .try_into().unwrap() which implies a range_check which could be avoided by making a variant of pow2 for each type, but it's probably better to wait for a feature of the language allowing us to do it automatically. What do you prefer? |
@Th0rgal Guess it is case specific then 🤔 , do as you believe is the best 😄 |
Okay, here is a summary:
|
Any idea why the root lock file is changed? |
Yes, I added math dependency to alexandria_merkle: [dependencies]
alexandria_math = { path = "../math" } I thought it would be cleaner than copy pasting the code, but I can do it if you prefer. |
Oh wow... My bad on that one, missed that toml file 😅 |
Implement efficient pow2 and pow10 using const arrays
Pull Request type
Please check the type of change your PR introduces:
What is the current behavior?
Currently, the implementation of pow2 and pow10 functions uses if/else branches, which is less efficient than using lookup tables.
Issue Number: N/A
What is the new behavior?
Does this introduce a breaking change?
Other information
This PR takes advantage of Cairo 2.7.0's reintroduction of "
dw
like hardcoded function results" via const arrays to implement efficient lookup tables for pow2 and pow10. These functions are commonly used in various projects, including Alexandria for bitshifting and in DeFi applications for handling ERC20 decimals. I introduced a u128 version (should be the one used in most usecases), and a u256 version for both pow2 and pow10. The u256 version of pow2 uses the u128 one.The new implementation significantly reduces gas usage. For example, I updated keccak implementation to use this new function and the
test_bytes_keccak
test saw a reduction in estimated gas usage from 2,399,388 to 1,289,988.closes #323