feat: speed up adding and expiring records in the DNSCache (#1490) · python-zeroconf/python-zeroconf@628b136
@@ -86,7 +86,8 @@ def _async_add(self, record: _DNSRecord) -> bool:
8686# replaces any existing records that are __eq__ to each other which
8787# removes the risk that accessing the cache from the wrong
8888# direction would return the old incorrect entry.
89-store = self.cache.setdefault(record.key, {})
89+if (store := self.cache.get(record.key)) is None:
90+store = self.cache[record.key] = {}
9091new = record not in store and not isinstance(record, DNSNsec)
9192store[record] = record
9293when = record.created + (record.ttl * 1000)
@@ -97,7 +98,9 @@ def _async_add(self, record: _DNSRecord) -> bool:
97989899if isinstance(record, DNSService):
99100service_record = record
100-self.service_cache.setdefault(record.server_key, {})[service_record] = service_record
101+if (service_store := self.service_cache.get(service_record.server_key)) is None:
102+service_store = self.service_cache[service_record.server_key] = {}
103+service_store[service_record] = service_record
101104return new
102105103106def async_add_records(self, entries: Iterable[DNSRecord]) -> bool:
@@ -145,14 +148,16 @@ def async_expire(self, now: _float) -> List[DNSRecord]:
145148expired: List[DNSRecord] = []
146149# Find any expired records and add them to the to-delete list
147150while self._expire_heap:
148-when, record = self._expire_heap[0]
151+when_record = self._expire_heap[0]
152+when = when_record[0]
149153if when > now:
150154break
151155heappop(self._expire_heap)
152156# Check if the record hasn't been re-added to the heap
153157# with a different expiration time as it will be removed
154158# later when it reaches the top of the heap and its
155159# expiration time is met.
160+record = when_record[1]
156161if self._expirations.get(record) == when:
157162expired.append(record)
158163