3
Avoid use of exceptions to detect invalid floats by flavorjones · Pull Request #...
source link: https://github.com/rails/rails/pull/43106
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Summary
Improves the performance of ActiveSupport::NumberHelper and ActionView::Helpers::NumberHelper formatters by avoiding the use of exceptions as flow control.
Other Information
Note that Float(..., exception: false)
is only available as of Ruby 2.7.
Benchmarks
I benchmarked this by calling ActiveSupport::NumberHelper.number_to_rounded
with:
- a Float
- a valid number string
- an invalid number string
Here are the results:
Calculating -------------------------------------
old float 13.865k (±22.7%) i/s - 123.120k in 9.884256s
Calculating -------------------------------------
new float 13.700k (±24.1%) i/s - 119.756k in 9.890457s
Comparison:
old float: 13865.4 i/s
new float: 13700.1 i/s - same-ish: difference falls within error
Calculating -------------------------------------
old valid 13.731k (±24.8%) i/s - 120.903k in 9.884648s
Calculating -------------------------------------
new valid 13.801k (±24.0%) i/s - 121.491k in 9.894559s
Comparison:
new valid: 13801.3 i/s
old valid: 13731.4 i/s - same-ish: difference falls within error
Calculating -------------------------------------
old invalid 204.829k (±20.9%) i/s - 1.437M in 9.384316s
Calculating -------------------------------------
new invalid 624.895k (±20.5%) i/s - 4.312M in 8.345591s
Comparison:
new invalid: 624895.1 i/s
old invalid: 204829.2 i/s - 3.05x (± 0.00) slower
The new signature is comparable or slightly faster for Floats and valid strings, and much wow faster on invalid strings.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK