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/ReverseFirst cop #128

Merged
merged 1 commit into from
Jun 11, 2020

Conversation

fatkodima
Copy link
Contributor

There is no need to reverse the whole array to get last n items in order from end to begin.

# bad
array.reverse.first(5)
array.reverse.first

# good
array.last(5).reverse
array.last

Benchmark

require 'bundler/inline'

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

ARRAY = (1..100).to_a

Benchmark.ips do |x|
  x.report('Array.last(n).reverse')  { ARRAY.last(5).reverse }
  x.report('Array.reverse.first(n)') { ARRAY.reverse.first(5) }
  x.compare!
end

Results

Warming up --------------------------------------
Array.last(n).reverse
                       515.468k i/100ms
Array.reverse.first(n)
                       101.975k i/100ms
Calculating -------------------------------------
Array.last(n).reverse
                          4.544M (± 8.7%) i/s -     22.681M in   5.034133s
Array.reverse.first(n)
                        913.988k (± 9.9%) i/s -      4.589M in   5.080680s

Comparison:
Array.last(n).reverse:  4543639.0 i/s
Array.reverse.first(n):   913988.0 i/s - 4.97x  (± 0.00) slower

Obviously, this scales linearly with array size.

@fatkodima
Copy link
Contributor Author

fatkodima commented Jun 11, 2020

Updated with missing tests.

@koic koic merged commit 7ec7689 into rubocop:master Jun 11, 2020
@koic
Copy link
Member

koic commented Jun 11, 2020

Thanks!

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