-
Notifications
You must be signed in to change notification settings - Fork 22k
Avoid use of exceptions to detect invalid floats #43106
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
Avoid use of exceptions to detect invalid floats #43106
Conversation
Tagging @p8 whose idea this was. 🙌 |
fd1e2da
to
2b831a1
Compare
Note that I've updated this PR to make a similar modification to ActionView::Helpers::NumberHelper. |
Use Kernel::Float(..., exceptions:false) instead of a rescue block in ActionView::Helpers::NumberHelper and ActiveSupport::NumberHelper::NumberConverter to slightly improve performance. Also remove documentation that incorrectly states ActiveSupport::NumberHelper supports the `raise:` option.
2b831a1
to
900ce92
Compare
Kernel::Float(..., exception: false)
in NumberConverter#valid_float?
Nice! 😄🙌 |
Float(number) | ||
rescue ArgumentError, TypeError | ||
false | ||
Float(number, exception: false) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hum, the return will be nil
instead of false
, but I don't think it's worth adding a || false
.
Thanks, also the perf impact is dependant on the stack size, so that 3X could be way larger in real word scenarios. |
rescue ArgumentError, TypeError | ||
raise InvalidNumberError, number if raise_error | ||
result = Float(number, exception: false) | ||
raise InvalidNumberError, number if result.nil? && raise_error |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fyi #43853
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👁️
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤦
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:Here are the results:
The new signature is comparable or slightly faster for Floats and valid strings, and much wow faster on invalid strings.