Skip to content

Commit f172129

Browse files
committed
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 rails#36052.
1 parent af4ca42 commit f172129

File tree

1 file changed

+7
-4
lines changed
  • activerecord/lib/active_record

1 file changed

+7
-4
lines changed

activerecord/lib/active_record/core.rb

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -837,17 +837,20 @@ def to_ary
837837
end
838838

839839
def init_internals
840-
@primary_key = self.class.primary_key
841840
@readonly = false
842841
@previously_new_record = false
843842
@destroyed = false
844843
@marked_for_destruction = false
845844
@destroyed_by_association = nil
846845
@_start_transaction_state = nil
847-
@strict_loading = self.class.strict_loading_by_default
848-
@strict_loading_mode = self.class.strict_loading_mode
849846

850-
self.class.define_attribute_methods
847+
klass = self.class
848+
849+
@primary_key = klass.primary_key
850+
@strict_loading = klass.strict_loading_by_default
851+
@strict_loading_mode = klass.strict_loading_mode
852+
853+
klass.define_attribute_methods
851854
end
852855

853856
def initialize_internals_callback

0 commit comments

Comments
 (0)