From efbca69ac4bca51c9b3e84be3af214caad041fb4 Mon Sep 17 00:00:00 2001 From: Sean Millichamp Date: Tue, 2 Apr 2024 16:42:48 +0000 Subject: [PATCH] Improve add_facts performance When making multiple add_facts calls to add facts to an already present and large set of target facts performance declines as more are added due to the initialization and copying of the large hashes each time. This change merges the added facts in place to the existing facts, which provides a slight performance improvement. !feature * **Minor add_facts optimization** Deep merge new facts into existing target fact hash, instead of creating and copying a new hash each time. --- lib/bolt/inventory/target.rb | 2 +- lib/bolt/util.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/bolt/inventory/target.rb b/lib/bolt/inventory/target.rb index 1edf94c702..abec9ce4ac 100644 --- a/lib/bolt/inventory/target.rb +++ b/lib/bolt/inventory/target.rb @@ -98,7 +98,7 @@ def facts def add_facts(new_facts = {}) validate_fact_names(new_facts) - @facts = Bolt::Util.deep_merge(@facts, new_facts) + Bolt::Util.deep_merge!(@facts, new_facts) end def features diff --git a/lib/bolt/util.rb b/lib/bolt/util.rb index a28c5d14a5..56a4615fa7 100644 --- a/lib/bolt/util.rb +++ b/lib/bolt/util.rb @@ -212,6 +212,17 @@ def deep_merge(hash1, hash2) hash1.merge(hash2, &recursive_merge) end + def deep_merge!(hash1, hash2) + recursive_merge = proc do |_key, h1, h2| + if h1.is_a?(Hash) && h2.is_a?(Hash) + h1.merge!(h2, &recursive_merge) + else + h2 + end + end + hash1.merge!(hash2, &recursive_merge) + end + # Accepts a Data object and returns a copy with all hash keys # modified by block. use &:to_s to stringify keys or &:to_sym to symbolize them def walk_keys(data, &block)