administrate icon indicating copy to clipboard operation
administrate copied to clipboard

Potential peformance improvements with Field::BelongsTo

Open paayaw0 opened this issue 1 year ago • 2 comments

This issue maybe have some overlaps with this and this

I was working on a project that uses administrate and noticed a performance issue with the Field::BelongsTo, where the associated record took too long to load up in the edit form. For more context the association in question is as follows:

class Employee
  belongs_to :company
end

class Company
  has_many :employees
end

So in the Employee edit form, I need to select a company that a particular employee belongs to. As the number of companies created increased I noticed a considerable delay in the edit form to the point where the page was unusable for a minute or so. Tracking down the issue led me to this line of code here

In a situation where thousands of associated objects need to be iterated upon one could imagine how this will overtime cause a significant lag in performance.

My current resolution was to create a custom field as explained in your documentation, implementing the .find_each query method and immediately noticed a significant improvement.

What I propose is the use of the active record method.find_each as defined here. This is a memory-friendly approach to iterating over large number of records.

Hopefully during the weekend I'll have the time to submit my suggestion upstream as PR with screenshots of benchmarked improvements but given that my solution is pretty simple I believe anyone with the time on their hands can easily implement this upstream.

paayaw0 avatar May 31 '24 04:05 paayaw0

Ah, interesting! Using .find_each instead makes sense to me. How did you get on with trying to open a PR for that?

nickcharlton avatar Sep 23 '24 14:09 nickcharlton

@paayaw0 I know this was a while ago, but do you have any more information you can share on how you fixed this?

JPrevost avatar Apr 16 '25 15:04 JPrevost