Skip to content

Commit

Permalink
Remove N+1 obj creation in flatten_arranged_rels
Browse files Browse the repository at this point in the history
The recursive nature of the original code, this meant that a new array
was created for every call of the method.

This new form now only creates 2 arrays, and speeds up the process to
flatten the rels by 2x in most cases.
  • Loading branch information
NickLaMuro committed Apr 22, 2018
1 parent 9f8c439 commit fcfd86d
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions app/models/relationship.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,15 @@ def resource_pair
#

def self.flatten_arranged_rels(relationships)
relationships.each_with_object([]) do |(rel, children), a|
a << rel
a.concat(flatten_arranged_rels(children))
result = relationships.keys
remaining_children = relationships.values
until remaining_children.empty?
remaining_children.pop.each do |rel, kids|
result << rel
remaining_children << kids
end
end
result
end

def self.arranged_rels_to_resources(relationships, initial = true)
Expand Down

0 comments on commit fcfd86d

Please sign in to comment.