Skip to content
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

Simpler power(_:) function? #153

Closed
oscbyspro opened this issue Dec 17, 2024 · 2 comments
Closed

Simpler power(_:) function? #153

oscbyspro opened this issue Dec 17, 2024 · 2 comments
Labels
brrr such code, much wow subtraction huh? where did it go?

Comments

@oscbyspro
Copy link
Owner

oscbyspro commented Dec 17, 2024

After some experiments in (#71), the difference between arbitrary integer a.power(b).times(c) and a.power(b, coefficient: c) appears small when the initial power is without heap allocation. The former is simpler to test and reason about, so I prefer it. There are at least two ways to prevent this heap allocation: (A) adding a static protocol requirement or (B) waiting for a small-integer optimization (#44) that puts it on the stack.

@oscbyspro oscbyspro added the subtraction huh? where did it go? label Dec 17, 2024
@oscbyspro
Copy link
Owner Author

oscbyspro commented Dec 17, 2024

Some values may benefit from static protocol requirements. 0, 1, and 10 are the first that come to mind. But I'm hoping that a small-integer optimization (#44) is the answer because it is a more general solution.

@oscbyspro oscbyspro added the brrr such code, much wow label Dec 17, 2024
@oscbyspro
Copy link
Owner Author

oscbyspro commented Dec 18, 2024

Looking at the assembly output of a similar Swift.UInt algorithm, it looks like the compiler turns the "coefficient" version into the "non-coefficient" version by setting the initial power to 1 and inserting an imul before the loop. As a result, the coefficient version contains one more instruction. Silly.

Edit: But this is only in -O mode. In -Osize they are basically identical, which means that we do get one multiplication for free in the "coefficient" version. Edit (again): Never mind, it isn't free because we still have to put the coefficient on the stack to call the function :(

oscbyspro added a commit that referenced this issue Dec 19, 2024
This patch simplifies exponentiation by replacing `power(_:coefficient:)` with `power(_:)`.
oscbyspro added a commit that referenced this issue Dec 19, 2024
* Simpler `power(_:)` function! (#153).

This patch simplifies exponentiation by replacing `power(_:coefficient:)` with `power(_:)`.

* Cleanup.

* Cleanup.

* Cleanup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
brrr such code, much wow subtraction huh? where did it go?
Projects
None yet
Development

No branches or pull requests

1 participant