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

Implement fast_float for String#to_f #15195

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

HertzDevil
Copy link
Contributor

@HertzDevil HertzDevil commented Nov 15, 2024

Resolves #11952.

This is a source port of https://github.com/fastfloat/fast_float, which is both locale-independent and platform-independent, meaning the special float values will work on MSYS2's MINGW64 environment too, as we are not calling LibC.strtod anymore. Additionally, non-ASCII whitespace characters are now stripped, just like #to_i.

The current implementation doesn't accept hexfloats.

Below is a basic benchmark that converts random Float32 strings:

require "benchmark"

f1 = 0.0
s = ""
f2 = 0.0

N = ENV["N"]?.try(&.to_i?) || 100000

Benchmark.ips do |b|
  b.report("ctrl") do
    N.times do
      f1 = rand(UInt64).unsafe_as(Float64)
      s = f1.to_s
    end
  end

  b.report("to_f") do
    N.times do
      f1 = rand(UInt64).unsafe_as(Float64)
      s = f1.to_s
      f2 = s.to_f64
    end
  end
end

Before:

ctrl  72.00  ( 13.89ms) (± 2.23%)  13.7MB/op        fastest
to_f  49.70  ( 20.12ms) (± 2.96%)  13.7MB/op   1.45× slower

After:

ctrl  72.81  ( 13.73ms) (± 2.37%)  13.7MB/op        fastest
to_f  63.39  ( 15.78ms) (± 2.56%)  13.7MB/op   1.15× slower

Thus fast_float brings the time down from 6.23ms to 2.05ms, a roughly 3x speedup, without any additional allocations.

@HertzDevil HertzDevil marked this pull request as ready for review November 18, 2024 10:49
@kostya
Copy link
Contributor

kostya commented Nov 19, 2024

I also added shard for this: https://github.com/kostya/fast_to_f

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

Successfully merging this pull request may close these issues.

Functions that depend on the current C locale
2 participants