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/Sum cop #137

Merged
merged 1 commit into from
Jul 18, 2020
Merged

Add new Performance/Sum cop #137

merged 1 commit into from
Jul 18, 2020

Conversation

fatkodima
Copy link
Contributor

Instead of custom implementations of array summation, we should use sum method, which is a lot faster.

# bad
[1, 2, 3].inject(:+)
[1, 2, 3].reduce(10, :+)
[1, 2, 3].reduce { |acc, elem| acc + elem }

# good
[1, 2, 3].sum
[1, 2, 3].sum(10)
[1, 2, 3].sum

Benchmark

# frozen_string_literal: true

require 'bundler/inline'

gemfile(true) do
  gem 'benchmark-ips'
end

RANGE = 1..10

Benchmark.ips do |x|
  x.report("reduce(:+)")   { RANGE.reduce(:+) }
  x.report("reduce { |sum, n| sum + n }")   { RANGE.reduce { |sum, n| sum + n } }
  x.report("sum") { RANGE.sum }

  x.compare!
end

Results

When RANGE = 1..10:

Comparison:
                 sum:  8472475.9 i/s
          reduce(:+):  1421098.7 i/s - 5.96x  (± 0.00) slower
reduce { |sum, n| sum + n }:  1274392.8 i/s - 6.65x  (± 0.00) slower

When RANGE=1..1000:

Comparison:
                 sum:  8309208.6 i/s
          reduce(:+):    19003.9 i/s - 437.24x  (± 0.00) slower
reduce { |sum, n| sum + n }:    15918.6 i/s - 521.98x  (± 0.00) slower

When RANGE=1..1_000_000:

Comparison:
                 sum:  8478595.9 i/s
          reduce(:+):       19.2 i/s - 442082.64x  (± 0.00) slower
reduce { |sum, n| sum + n }:       17.0 i/s - 498855.95x  (± 0.00) slower

We cannot safely autocorrect when initial value is not provided, because, for example, if we convert code

('a'..'z').to_a.reduce { |acc, elem| acc + elem }

into code

('a'..'z').to_a.sum

and this will result in TypeError (String can't be coerced into Integer), because for sum method initial is 0 if not specified explicitly.

When initial value is provided - we can safely autocorrect.

@bbatsov
Copy link
Contributor

bbatsov commented Jun 12, 2020

Good work overall. As usual - it's nice to attach some references to the cops.

@bbatsov
Copy link
Contributor

bbatsov commented Jun 12, 2020

Btw, it can also be argued that's a matter of style, not just performance.

@fatkodima
Copy link
Contributor Author

Updated with:

  1. better cop description, as suggested
  2. link reference. There is just one non finished PR mentioning Enumerable#sum for the whole fast-ruby, so I added mentioned link (didn't find better on the internets).

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.

2 participants