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

A Cop to detect wasteful initializations #71

Open
ashmaroli opened this issue Jul 14, 2019 · 4 comments
Open

A Cop to detect wasteful initializations #71

ashmaroli opened this issue Jul 14, 2019 · 4 comments

Comments

@ashmaroli
Copy link

Is your feature request related to a problem? Please describe.

I frequently encounter non-memoized method definitions that involve generation of a constant object that doesn't depend on the state of the Class / Module.

Example

Given that there's a class with following instance methods:

def fallback_data(config)
  {
    :foo => "bar",
    :sit => "amet",
  }.merge(config)
end

def cross_over(type)
  return unless %w[lorem ipsum dolor sit amet alpha].include?(type)

  # proceed doing stuff
end

The Hash generated in :fallback_data and the intermediate array in :cross_over are both going to remain the same in any given instance of the Class. Multiple calls to these methods are going to allocate those objects unnecessarily .

Describe the solution you'd like

Flag such methods and recommend stashing the constant-value objects as "constants", or consider memoizing them as "singleton methods"

@Drenmi
Copy link
Contributor

Drenmi commented Jul 15, 2019

Hi, @ashmaroli!

The performance cops have recently been moved to their own repository. Please help move your issue over there. Thank you! 🙇

@Drenmi Drenmi closed this as completed Jul 15, 2019
@ashmaroli
Copy link
Author

@Drenmi Will you be able to transfer this issue using the GitHub UI?
https://help.github.com/en/articles/transferring-an-issue-to-another-repository

@Drenmi Drenmi transferred this issue from rubocop/rubocop Jul 15, 2019
@Drenmi Drenmi reopened this Jul 15, 2019
@Drenmi
Copy link
Contributor

Drenmi commented Jul 15, 2019

Good suggestion @ashmaroli! That's a neat feature which I was not aware of. 🙂

@ashmaroli
Copy link
Author

You're welcome, Ted. 🙂

exoego added a commit to exoego/rubocop-performance that referenced this issue Sep 4, 2022
exoego added a commit to exoego/rubocop-performance that referenced this issue Sep 5, 2022
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

No branches or pull requests

2 participants