Skip to content

Commit 628b136

Browse files
authored
feat: speed up adding and expiring records in the DNSCache (#1490)
1 parent 854fef6 commit 628b136

2 files changed

Lines changed: 12 additions & 5 deletions

File tree

src/zeroconf/_cache.pxd

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ cdef class DNSCache:
3939
@cython.locals(store=cython.dict)
4040
cpdef DNSRecord async_get_unique(self, DNSRecord entry)
4141

42-
@cython.locals(record=DNSRecord)
42+
@cython.locals(record=DNSRecord, when_record=tuple, when=double)
4343
cpdef list async_expire(self, double now)
4444

4545
@cython.locals(records=cython.dict, record=DNSRecord)
@@ -57,8 +57,10 @@ cdef class DNSCache:
5757

5858
@cython.locals(
5959
store=cython.dict,
60+
service_store=cython.dict,
6061
service_record=DNSService,
61-
when=object
62+
when=object,
63+
new=bint
6264
)
6365
cdef bint _async_add(self, DNSRecord record)
6466

src/zeroconf/_cache.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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] = {}
9091
new = record not in store and not isinstance(record, DNSNsec)
9192
store[record] = record
9293
when = record.created + (record.ttl * 1000)
@@ -97,7 +98,9 @@ def _async_add(self, record: _DNSRecord) -> bool:
9798

9899
if isinstance(record, DNSService):
99100
service_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
101104
return new
102105

103106
def async_add_records(self, entries: Iterable[DNSRecord]) -> bool:
@@ -145,14 +148,16 @@ def async_expire(self, now: _float) -> List[DNSRecord]:
145148
expired: List[DNSRecord] = []
146149
# Find any expired records and add them to the to-delete list
147150
while self._expire_heap:
148-
when, record = self._expire_heap[0]
151+
when_record = self._expire_heap[0]
152+
when = when_record[0]
149153
if when > now:
150154
break
151155
heappop(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]
156161
if self._expirations.get(record) == when:
157162
expired.append(record)
158163

0 commit comments

Comments
 (0)