Skip to content

BigDecimal#to_f is slow when it has large n_significant_digits #515

Description

@tompng

BigDecimal#to_f is accurate, it returns exact nearest float value, but may be extremely slow in some case.

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

If BigDecimal#to_f is optimized, we can remove workaround like #514

Activity

  1. changed the title [-]`BigDecimal#to_f` is slow when it has n_significant_digits[/-] [+]`BigDecimal#to_f` is slow when it has large n_significant_digits[/+] on Apr 3, 2026
  2. byroot commented on Apr 7, 2026

    @byroot
    Member

    I looked a bit at this, and it seems that after #519 that particular slowness is no more?

    On my machine:

    before:

     1.96 real         1.58 user         0.02 sys
    

    after (with reverting 3bf735f):

     0.64 real         0.34 user         0.02 sys
    

    Now most of the profile is VP_ulltoa and memcpy in VpToString, with a little bit of ruby_strtod.

    https://share.firefox.dev/4sVGaHo

    If we want to optimize this further, JSON now use a faster algorithm: ruby/json#767, but it's under MIT

  3. tompng commented on Apr 8, 2026

    @tompng
    MemberAuthor

    Looks like it is basically resolved.
    Reverted the workaround for to_f(#514) in #522

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions