state-machines / state_machines

Adds support for creating state machines for attributes on any Ruby class
https://github.com/state-machines/state_machines
MIT License
814 stars 91 forks source link

Optimize owner_class_ancestor_has_method? #50

Closed casperisfine closed 7 years ago

casperisfine commented 7 years ago

I was investigating into our app boot time today, and I found something interesting:

==================================
  Mode: wall(1000)
  Samples: 22 (21.43% miss rate)
  GC: 2 (9.09%)
==================================
     TOTAL    (pct)     SAMPLES    (pct)     FRAME
         6  (27.3%)           5  (22.7%)     StateMachines::Machine#owner_class_ancestor_has_method?
         5  (22.7%)           5  (22.7%)     block in StateMachines::Integrations::Base::ClassMethods#matches?
         1   (4.5%)           1   (4.5%)     block in ActiveSupport::Dependencies#search_for_file
         1   (4.5%)           1   (4.5%)     Hash#assert_valid_keys
         1   (4.5%)           1   (4.5%)     StateMachines::NodeCollection#value
         1   (4.5%)           1   (4.5%)     StateMachines::Machine#define_helper
         1   (4.5%)           1   (4.5%)     ActiveRecord::DynamicMatchers#respond_to?
         1   (4.5%)           1   (4.5%)     block in StateMachines::Machine#owner_class_ancestor_has_method?
         1   (4.5%)           1   (4.5%)     ActiveSupport::Callbacks::ClassMethods#get_callbacks
         1   (4.5%)           1   (4.5%)     ActiveSupport::Concern#append_features

I couldn't find a way to optimize the whole method, but I found a way to makes it return faster if there is no conflicts to find (which I assume is most cases).

==================================
  Mode: wall(1000)
  Samples: 18 (41.94% miss rate)
  GC: 2 (11.11%)
==================================
     TOTAL    (pct)     SAMPLES    (pct)     FRAME
         3  (16.7%)           3  (16.7%)     block in StateMachines::Integrations::Base::ClassMethods#matches?
        15  (83.3%)           2  (11.1%)     <class:Comment>
         1   (5.6%)           1   (5.6%)     block in StateMachines::Machine#owner_class=
         1   (5.6%)           1   (5.6%)     StateMachines::Event#transition
         2  (11.1%)           1   (5.6%)     StateMachines::Integrations::ActiveRecord#owner_class_ancestor_has_method?
         1   (5.6%)           1   (5.6%)     StateMachines::Machine#owner_class_has_method?
         1   (5.6%)           1   (5.6%)     block (3 levels) in Class#class_attribute
         3  (16.7%)           1   (5.6%)     ActiveSupport::Concern#append_features
         1   (5.6%)           1   (5.6%)     Hash#assert_valid_keys
         1   (5.6%)           1   (5.6%)     <module:Comment>

@seuros @rafaelfranca what do you think?