Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

STI slow, result of ActiveRecord#find_sti_class should be cached!

#5403

Hi,

after getting perftools.rb running with 1.9.2 and rails3rc i found that a lot of cycles are burned inside find_sti_class (actually compute_type). this is caused by looking up a constant fails to load:

base.rb:1141

        # Build a list of candidates to search for
        candidates = []
        name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
        candidates << type_name

class A < ActiveRecord::Base
end

class B < A
end

this will set candidates to ["A::B", "B"], now "A::B" will go though the long codepath of constantize - and it will everytime a B is instantiated from the database as the const A::B will never come into existance and we don't do negative caching.

my suggestion would be to add a class level cache to the find_sti_class method. that will improve performace of largish queries with sti.

i would write a patch myself, but failed to get the AR testsuite pass on my box.

re,
thies

Reported by thieso (at gmail) · August 18th, 2010 @ 04:07 PM

State: resolved
Milestone: 3.0.2
Assigned to: Jeremy Kemper Jeremy Kemper
Importance: Low

Activity

  1. thieso (at gmail)
  2. thieso (at gmail)
    thieso (at gmail)
    • Tag changed from active_record, performance, sti to active_record, patch, performance, sti

    August 18th, 2010 @ 04:38 PM

  3. Jeremy Kemper
    Jeremy Kemper
    • Milestone cleared.
    • State changed from new to open
    • Assigned user set to Jeremy Kemper
    • Importance changed from to Low

    Good idea. However, Thieso's patch will break in development mode since the memoized classes will be reloaded. We can use ActiveSupport::Dependencies.constantize(name) to memoize the lookup within the duration of a request.

    August 19th, 2010 @ 05:04 PM

  4. Jeremy Kemper
  5. Andrew White
    Andrew White

    We can speed this up by another 30% by optimizing the case where store_full_sti_class is true. This has been the default for some time now so should be the case for the vast majority of apps.

    August 19th, 2010 @ 09:54 PM

  6. Repository
  7. Repository
  8. Jeremy Kemper