|
| 1 | +# ActiveRecord performance optimisation |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +When an AcriveRecord query is executed in a loop, it potentially an n+1 problem. |
| 6 | +This query identifies situations where an ActiveRecord query execution could be pulled out of a loop. |
| 7 | + |
| 8 | +## Recommendation |
| 9 | +Pull the query out of the loop, thus replacing the many calls with a single one. |
| 10 | + |
| 11 | +## Examples |
| 12 | + |
| 13 | +### Suboptimal |
| 14 | + |
| 15 | +The following (suboptimal) example code queries the User object in each iteration of the loop: |
| 16 | + |
| 17 | +```ruby |
| 18 | +repo_names_by_owner.map do |owner_slug, repo_names| |
| 19 | + owner_id, owner_type = User.where(login: owner_slug).pluck(:id, :type).first |
| 20 | + owner_type = owner_type == "User" ? "USER" : "ORGANIZATION" |
| 21 | + rel_conditions = { owner_id: owner_id, name: repo_names } |
| 22 | + |
| 23 | + nwo_rel = nwo_rel.or(RepositorySecurityCenterConfig.where(rel_conditions)) unless neg |
| 24 | + nwo_rel = nwo_rel.and(RepositorySecurityCenterConfig.where.not(rel_conditions)) if neg |
| 25 | + end |
| 26 | +``` |
| 27 | +### Fixed |
| 28 | + |
| 29 | +To improve the performance, we instead query the User object once outside the loop, gathereing all necessary information: |
| 30 | + |
| 31 | +```ruby |
| 32 | +# Preload User data |
| 33 | +user_data = User.where(login: repo_names_by_owner.keys).pluck(:login, :id, :type).to_h do |login, id, type| |
| 34 | + [login, { id: id, type: type == "User" ? "USER" : "ORGANIZATION" }] |
| 35 | + end |
| 36 | + |
| 37 | +repo_names_by_owner.each do |owner_slug, repo_names| |
| 38 | + owner_info = user_data[owner_slug] |
| 39 | + owner_id = owner_info[:id] |
| 40 | + owner_type = owner_info[:type] |
| 41 | + rel_conditions = { owner_id: owner_id, name: repo_names } |
| 42 | + |
| 43 | + nwo_rel = nwo_rel.or(RepositorySecurityCenterConfig.where(rel_conditions)) unless neg |
| 44 | + nwo_rel = nwo_rel.and(RepositorySecurityCenterConfig.where.not(rel_conditions)) if neg |
| 45 | +end |
| 46 | +``` |
0 commit comments