• R
    Improve performance for loaded association's `first` · c2a3fdc0
    Ryuta Kamizono 提交于
    Delegate to scope values (e.g. `offset_value`, `order_values`) is slow.
    
    We can avoid that if records are already loaded.
    
    ```ruby
    class Post < ActiveRecord::Base
      has_many :comments
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :post
      has_many :likes
    end
    
    class Like < ActiveRecord::Base
      belongs_to :post
    end
    
    10.times { Post.create! }
    30.times { |i| Comment.create!(post_id: 1 + i % 10) }
    150.times { |i |Like.create!(comment_id: 1 + i % 30) }
    
    post = Post.includes(comments: :likes).last
    
    result = Benchmark.measure do
      100.times { post.comments.each { |c| c.likes.first.id } }
    end
    
    puts
    puts result
    ```
    
    Before:
    
    ```
      0.013542   0.000582   0.014124 (  0.014125)
    ```
    
    After:
    
    ```
      0.000938   0.000017   0.000955 (  0.000952)
    ```
    
    Fixes #38252.
    c2a3fdc0
collection_proxy.rb 36.3 KB