Skip to content

Commit efbca69

Browse files
committed
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.
1 parent 4b30c39 commit efbca69

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/bolt/inventory/target.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def facts
9898

9999
def add_facts(new_facts = {})
100100
validate_fact_names(new_facts)
101-
@facts = Bolt::Util.deep_merge(@facts, new_facts)
101+
Bolt::Util.deep_merge!(@facts, new_facts)
102102
end
103103

104104
def features

lib/bolt/util.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,17 @@ def deep_merge(hash1, hash2)
212212
hash1.merge(hash2, &recursive_merge)
213213
end
214214

215+
def deep_merge!(hash1, hash2)
216+
recursive_merge = proc do |_key, h1, h2|
217+
if h1.is_a?(Hash) && h2.is_a?(Hash)
218+
h1.merge!(h2, &recursive_merge)
219+
else
220+
h2
221+
end
222+
end
223+
hash1.merge!(hash2, &recursive_merge)
224+
end
225+
215226
# Accepts a Data object and returns a copy with all hash keys
216227
# modified by block. use &:to_s to stringify keys or &:to_sym to symbolize them
217228
def walk_keys(data, &block)

0 commit comments

Comments
 (0)