Ruby Floats: When 2.6x Faster Is Actually Slower (and Then Faster Again)

26 days ago 4 views Closer to Code mensfeld.pl

Table of Contents

  • 1 Finding the "Perfect" Algorithm
  • 2 The Implementation
  • 3 The First Benchmark
  • 4 The Second Benchmark
  • 5 What Went Wrong
  • 6 Trying to Have It Both Ways
  • 7 Update: It Worked After All7.1 New Benchmark Results7.2 The PR
  • 7.1 New Benchmark Results
  • 7.2 The PR
  • 8 Summary
  • 9 References

Update: This article originally concluded that Eisel-Lemire wasn't worth it for Ruby. I was wrong. After revisiting the problem, I found a way to make it work - and submitted a PR to Ruby. Read the full update at the end.

Recently, I submitted a PR to Ruby that optimizes Float#to_s using the Ryu algorithm, achieving 2-4x performance improvements for float-to-string conversion. While that work deserves its own article, this article is about what happened when I tried to optimize the other direction: string-to-float parsing.

Float#to_s

String-to-float seemed like an equally promising target. It's a fundamental operation used everywhere - parsing JSON, reading configuration files, processing CSV data, and handling user input. Since the Ryu optimization worked so well for float-to-string, surely the reverse direction would yield similar gains?

I did my research. I