Call `self.class` only once in `init_internals`

Calling `self.class` multiple times is not cheap.

```ruby
class A
  def self.foo
  end

  def foo1
    self.class.foo
    self.class.foo
    self.class.foo
    self.class.foo
  end

  def foo2
    klass = self.class
    klass.foo
    klass.foo
    klass.foo
    klass.foo
  end
end

a = A.new

Benchmark.ips do |x|
  x.report("foo1") { a.foo1 }
  x.report("foo2") { a.foo2 }
end
```

```
Warming up --------------------------------------
                foo1   341.701k i/100ms
                foo2   414.000k i/100ms
Calculating -------------------------------------
                foo1      3.194M (± 5.4%) i/s -     16.060M in   5.044653s
                foo2      4.276M (± 3.8%) i/s -     21.528M in   5.041999s
```

Similar with #36052.
This commit is contained in:
Ryuta Kamizono 2021-03-28 11:10:24 +09:00
parent af4ca424eb
commit f172129256
1 changed files with 7 additions and 4 deletions

View File

@ -837,17 +837,20 @@ module ActiveRecord
end
def init_internals
@primary_key = self.class.primary_key
@readonly = false
@previously_new_record = false
@destroyed = false
@marked_for_destruction = false
@destroyed_by_association = nil
@_start_transaction_state = nil
@strict_loading = self.class.strict_loading_by_default
@strict_loading_mode = self.class.strict_loading_mode
self.class.define_attribute_methods
klass = self.class
@primary_key = klass.primary_key
@strict_loading = klass.strict_loading_by_default
@strict_loading_mode = klass.strict_loading_mode
klass.define_attribute_methods
end
def initialize_internals_callback