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

Avoid two clones in 'reduce'. #98

Merged
merged 5 commits into from
Jun 23, 2022
Merged

Avoid two clones in 'reduce'. #98

merged 5 commits into from
Jun 23, 2022

Conversation

lemmih
Copy link
Contributor

@lemmih lemmih commented Jul 17, 2021

Hi,

reduce needlessly clones the numerator and denominator. The "proper" way to fix this would be to add a new trait bound but that is not backwards compatible. This PR proposes a temporary fix: Take the values and leave behind zeroes. This avoids cloning and T::zero() usually doesn't involve heap allocations (at least they don't for BigInt). All in all, this PR improves performance by about 10% (1150ns -> 1050ns) when creating values from small BigInts (tested on an M1).
Creating a Ratio<BigInt> is still about 10x slower than Ratio<isize> but that is entirely due to problems in num-bigint.

Note: I copied the rng module from num-bigint.

Note: Adding a NumAssignRef bound would get rid of g.clone().

@cmpute
Copy link

cmpute commented Jan 11, 2022

There are also many other functions that use clone(). I will also vote for adding NumAssignRef or NumRef bound to the type. Although it will be a break change, it's quite worth it

@cuviper
Copy link
Member

cuviper commented Jun 23, 2022

@cmpute

Although it will be a break change, it's quite worth it

I don't take breaking changes lightly. Maybe we could add those bounds with a semver bump, but not right now.

@cuviper
Copy link
Member

cuviper commented Jun 23, 2022

Thanks for the PR! I moved the benchmarks to a CI crate so rand doesn't look like a public feature, nor affect MSRV as a dev-dependency (which can't be optional). I also added the same replace-zero trick to the final sign normalization.

bors r+

@bors
Copy link
Contributor

bors bot commented Jun 23, 2022

@bors bors bot merged commit 08ad135 into rust-num:master Jun 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants