Skip to content

Commit

Permalink
Improve add_facts performance
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
seanmil committed Apr 3, 2024
1 parent 4b30c39 commit efbca69
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/bolt/inventory/target.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions lib/bolt/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit efbca69

Please sign in to comment.