From 708fd26720a82d09c40babbc1ddb0d2dcac5323e Mon Sep 17 00:00:00 2001 From: Adam Grare Date: Sat, 1 Apr 2017 14:22:13 -0400 Subject: [PATCH] Merge pull request #14542 from Ladas/optimize_store_ids_for_new_records Optimize store_ids_for_new_records by getting rid of the O(n^2) lookups (cherry picked from commit 053c16e673d1ba73b98b6ebf73d98f46d2853c75) --- .../ems_refresh/save_inventory_helper.rb | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/app/models/ems_refresh/save_inventory_helper.rb b/app/models/ems_refresh/save_inventory_helper.rb index fe041d8a1c6..cd132d363c9 100644 --- a/app/models/ems_refresh/save_inventory_helper.rb +++ b/app/models/ems_refresh/save_inventory_helper.rb @@ -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?