FastFloatLemire
Eisel-Lemire algorithm for string-to-float conversion in Ruby.
About
This gem implements the Eisel-Lemire algorithm with additional fast paths for common number formats.
| Number Type | vs String#to_f |
|---|---|
Simple decimals ("1.5", "3.14") |
~7% faster |
Prices ("9.99", "19.95") |
~3% faster |
Scientific ("1e5") |
~6% slower |
Complex ("3.141592653589793") |
~2.8x faster |
Optimizations
The implementation includes several fast paths that bypass the full Eisel-Lemire algorithm:
-
Small integer fast path - handles
"5","42","-123"(up to 3 digits) -
Simple decimal fast path - handles
"1.5","9.99","199.95"(up to 3+3 digits) - Exact power-of-10 fast path - uses precomputed exact powers of 10 (10^0 to 10^22)
-
Removed overhead - no
strlen(), single whitespace skip
These optimizations are based on insights from Nigel Tao's Eisel-Lemire blog post.
Installation
gem install fast_float_lemireOr add to your Gemfile:
gem 'fast_float_lemire'Usage
require 'fast_float_lemire'
FastFloatLemire.parse("3.141592653589793") #=> 3.141592653589793
FastFloatLemire.parse("1.5") #=> 1.5
FastFloatLemire.parse("1e10") #=> 10000000000.0
# Bulk parsing
FastFloatLemire.parse_array(["1.0", "2.0", "3.14"]) #=> [1.0, 2.0, 3.14]Benchmarks
Run benchmarks with:
bundle exec ruby benchmarks/comparison.rbReferences
- Eisel-Lemire paper - "Number Parsing at a Gigabyte per Second"
- fast_float C++ library
- Go implementation
License
MIT