Skip to content

Commit

Permalink
Merge pull request ManageIQ#14542 from Ladas/optimize_store_ids_for_n…
Browse files Browse the repository at this point in the history
…ew_records

Optimize store_ids_for_new_records by getting rid of the O(n^2) lookups
  • Loading branch information
agrare committed Apr 1, 2017
2 parents 85ce759 + b4c143a commit 053c16e
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions app/models/ems_refresh/save_inventory_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,27 @@ def save_child_inventory(obj, hashes, child_keys, *args)
end

def store_ids_for_new_records(records, hashes, keys)
return if records.blank?

keys = Array(keys)
hashes.each do |h|
r = records.detect { |r| keys.all? { |k| r.send(k) == r.class.type_for_attribute(k.to_s).cast(h[k]) } }
h[:id] = r.id
# Lets first index the hashes based on keys, so we can do O(1) lookups
record_index = records.index_by { |record| build_index_from_record(keys, record) }
record_class = records.first.class.base_class

hashes.each do |hash|
record = record_index[build_index_from_hash(keys, hash, record_class)]
hash[:id] = record.id
end
end

def build_index_from_hash(keys, hash, record_class)
keys.map { |key| record_class.type_for_attribute(key.to_s).cast(hash[key]) }
end

def build_index_from_record(keys, record)
keys.map { |key| record.send(key) }
end

def link_children_references(records)
records.each do |rec|
parent = records.detect { |r| r.manager_ref == rec.parent_ref } if rec.parent_ref.present?
Expand Down

0 comments on commit 053c16e

Please sign in to comment.