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

Add new Performance/BigDecimalWithNumericArgument cop #129

Merged
merged 1 commit into from
Jun 8, 2020

Conversation

fatkodima
Copy link
Contributor

This is a simple one.

Related link - fastruby/fast-ruby#172

I believe there is a better name for this cop.

It is faster to pass string argument to BigDecimal than numeric arguments.

# bad
BigDecimal(1, 2)
BigDecimal(1.2, 3, exception: true)

# good
BigDecimal('1', 2)
BigDecimal('1.2', 3, exception: true)

Benchmark

require 'benchmark/ips'
require 'bigdecimal'

Benchmark.ips do |x|
  x.report("BigDecimal('1')")  { BigDecimal('1') }
  x.report("BigDecimal(1)")    { BigDecimal(1) }
  x.compare!
end

Benchmark.ips do |x|
  x.report("BigDecimal('1.0', 2)")  { BigDecimal('1.0', 2) }
  x.report("BigDecimal(1.0, 2)")    { BigDecimal(1.0, 2) }
  x.compare!
end

Results

Warming up --------------------------------------
     BigDecimal('1')   179.524k i/100ms
       BigDecimal(1)   114.825k i/100ms
Calculating -------------------------------------
     BigDecimal('1')      1.782M (± 3.9%) i/s -      8.976M in   5.046628s
       BigDecimal(1)      1.107M (± 6.5%) i/s -      5.512M in   5.002115s

Comparison:
     BigDecimal('1'):  1781639.0 i/s
       BigDecimal(1):  1106879.7 i/s - 1.61x  (± 0.00) slower

Warming up --------------------------------------
BigDecimal('1.0', 2)   151.605k i/100ms
  BigDecimal(1.0, 2)    34.490k i/100ms
Calculating -------------------------------------
BigDecimal('1.0', 2)      1.519M (± 4.6%) i/s -      7.580M in   5.001610s
  BigDecimal(1.0, 2)    339.573k (± 5.0%) i/s -      1.724M in   5.093169s

Comparison:
BigDecimal('1.0', 2):  1519109.1 i/s
  BigDecimal(1.0, 2):   339573.1 i/s - 4.47x  (± 0.00) slower

@fatkodima
Copy link
Contributor Author

Updated.

@fatkodima
Copy link
Contributor Author

Updated with new name.

@fatkodima fatkodima changed the title Add new Performance/BigDecimalString cop Add new Performance/BigDecimalWithNumericArgument cop Jun 8, 2020
@koic koic merged commit 0591cfd into rubocop:master Jun 8, 2020
@koic
Copy link
Member

koic commented Jun 8, 2020

Great activity!

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

Successfully merging this pull request may close these issues.

None yet

2 participants