Skip to content

Commit ad93f34

Browse files
committed
perf: skip QuestionHistory expire sweep when nothing can be reclaimed
1 parent fec39ac commit ad93f34

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

src/zeroconf/_history.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,16 @@ def __init__(self) -> None:
4141
def add_question_at_time(self, question: DNSQuestion, now: _float, known_answers: set[DNSRecord]) -> None:
4242
"""Remember a question with known answers."""
4343
# Bound history size between the periodic 10s cleanup ticks. When at
44-
# cap, first drop entries past the duplicate-suppression window; if
45-
# still at cap, evict the oldest insertion (dict is ordered).
44+
# cap, peek at the oldest insertion (dict is ordered) — only run the
45+
# full O(n) async_expire sweep if it could actually reclaim something,
46+
# else a sustained flood at cap turns each insert into a wasted scan.
4647
if question not in self._history and len(self._history) >= _MAX_QUESTION_HISTORY_ENTRIES:
47-
self.async_expire(now)
48+
oldest = next(iter(self._history))
49+
oldest_than, _ = self._history[oldest]
50+
if now - oldest_than > _DUPLICATE_QUESTION_INTERVAL:
51+
self.async_expire(now)
4852
while len(self._history) >= _MAX_QUESTION_HISTORY_ENTRIES:
49-
oldest = next(iter(self._history))
50-
del self._history[oldest]
53+
del self._history[next(iter(self._history))]
5154
self._history[question] = (now, known_answers)
5255

5356
def suppresses(self, question: DNSQuestion, now: _float, known_answers: set[DNSRecord]) -> bool:

0 commit comments

Comments
 (0)