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.

ActiveRecord::Relation#to_a should be cachable

#3594

Hey,

Right now there's performance issue in ActiveRecord::Relation#to_a:

@posts = Post.all { ... }

Returns a relation. Ok, then if we do something like:

@posts.map { ... }

Relation#to_a gets called and the records are initialized and loaded, this is ok, but if we do:

@posts.each { ... }

The records will be initialized all over again. This patch fixes this by adding memoization to Relation#to_a and unmemoizing when Base#all gets called.

@posts = Post.all

@posts.map { ... } # All records

@posts = Post.all :limit => 1

@posts.map { ... } # Only the first record

Reported by Emilio Tagua · December 17th, 2009 @ 06:13 PM

State: resolved
Milestone: none
Assigned to: Emilio Tagua Emilio Tagua
Importance: Low

Activity

  1. David Trasbo
    David Trasbo
    • Assigned user set to Ryan Bigg

    This has been solved - not by using memoization though:

    def to_a
      return @records if loaded?
    
      @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)
    
      # ...
    
      @loaded = true
      @records
    end
    
    def loaded?
      @loaded
    end
    

    This ticket can be closed.

    June 13th, 2010 @ 08:02 PM

  2. Emilio Tagua
    Emilio Tagua
    • State changed from new to resolved
    • Assigned user changed from Ryan Bigg to Emilio Tagua

    June 13th, 2010 @ 11:03 PM