Skip to content

Commit e825e61

Browse files
authored
Avoid per-key hash lookup when excluded_keys is empty (#318)
* Avoid per-key hash lookup when excluded_keys is empty Store nil instead of an empty hash when no excluded_keys are configured (the default) and use safe navigation (&.key?) in the hot loop. This avoids an unnecessary hash lookup for every key at every level of the statistics tree. Benchmarked at ~39% faster for the default (empty) case with ~200 keys, with no penalty when exclusions are configured. * Skip hash construction when excluded_keys is empty Avoid allocating and freezing an empty hash in the constructor when no exclusions are configured, as suggested by Copilot review.
1 parent d1ad337 commit e825e61

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

lib/karafka/core/monitoring/statistics_decorator.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,11 @@ def initialize(excluded_keys: [])
3434
@previous_at = monotonic_now.round
3535
# Cache for memoized suffix keys to avoid repeated string allocations
3636
@suffix_keys_cache = {}
37-
# Frozen hash for O(1) key exclusion lookup
38-
@excluded_keys = excluded_keys.each_with_object({}) { |k, h| h[k] = true }.freeze
37+
# Frozen hash for O(1) key exclusion lookup, nil when empty to avoid per-key
38+
# lookups in the hot loop when no exclusions are configured
39+
@excluded_keys = unless excluded_keys.empty?
40+
excluded_keys.each_with_object({}) { |k, h| h[k] = true }.freeze
41+
end
3942
end
4043

4144
# @param emited_stats [Hash] original emited statistics
@@ -87,7 +90,7 @@ def diff(previous, current, pw, pw_start, change_d)
8790
pw_size = pw_start
8891

8992
current.each_pair do |key, value|
90-
next if excluded.key?(key)
93+
next if excluded&.key?(key)
9194

9295
if value.is_a?(Hash)
9396
diff(filled_previous[key], value, pw, pw_size, change_d)

0 commit comments

Comments
 (0)