Skip to content

Add a workaround for slow BigDecimal#to_f when it has large N_significant_digits#514

Merged
tompng merged 1 commit intoruby:masterfrom
tompng:rough_fast_to_f
Apr 3, 2026
Merged

Add a workaround for slow BigDecimal#to_f when it has large N_significant_digits#514
tompng merged 1 commit intoruby:masterfrom
tompng:rough_fast_to_f

Conversation

@tompng
Copy link
Copy Markdown
Member

@tompng tompng commented Apr 2, 2026

BigDecimal#to_f is accurate, it returns exact nearest float value, but may be extremely slow in some case.
BigMath methods needs workaround like this:

irb(main):003> x = BigDecimal(1).div(7, 10000); 10000.times{(x - it).to_f}
processing time: 1.746866s
=> 10000
irb(main):004> x = BigDecimal(1).div(7, 10000); 10000.times{(x - it).mult(1, 20).to_f}
processing time: 0.053746s

In my environment, rake test time reduced from 4.8..4.9 seconds to 4.5..4.7 seconds.

The root cause is not fixed. It'd be better to optimize BigDecimal#to_f in the future.

@tompng tompng merged commit 3bf735f into ruby:master Apr 3, 2026
84 checks passed
@tompng tompng deleted the rough_fast_to_f branch April 3, 2026 13:42
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.

1 participant