Skip to content

Request: Object Shape (ivar initialization order) check #515

@schneems

Description

@schneems

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

A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

In Ruby 3.2+ there's a concept of "object shapes" where the order of initialization of instance variables affects performance of Ruby code https://www.youtube.com/watch?v=0lg9Y8gj3FI. The short version is that if you have code that looks like this:

class MyClass
  ...

  def foo
    @foo ||= get_foo
  end
  
  def bar
    @bar ||= get_bar
  end
end

It will generate two different "object shapes" based on which method is called first. The solution is to initialize those values consistently up front

class MyClass
  def initialize(...)
     @foo = nil
     @bar = nil
  end
  # ...
end

With this updated code, all instances of this class will have the same object shape and it's better for performance.

Describe the solution you'd like

Scan code for ivar creation that's not in an initialize method, verify that somewhere in the code, that same named ivar is also set to nil in an initialize method.

I know this gets hairy fast due to the flexability of Ruby, perhaps we make two rules "obviously bad usage" and "very agressive warnings that you might have to disable a lot" and only enable the "obviously bad usage" by default.

Describe alternatives you've considered

Manually scanning. But a lot of people don't know about it. See puma/puma#3714 for an IRL fix.

Additional context

Robocop meme reference!

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions