Optimize _async_track_event for the single key common case (#115242)

This commit is contained in:
J. Nick Koston 2024-04-09 07:04:50 -10:00 committed by GitHub
parent 1de1e413a9
commit 11af7d91ff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -401,9 +401,6 @@ def _async_track_event(
if not keys:
return _remove_empty_listener
if isinstance(keys, str):
keys = [keys]
hass_data = hass.data
callbacks_key = tracker.callbacks_key
@ -422,11 +419,23 @@ def _async_track_event(
job = HassJob(action, f"track {tracker.event_type} event {keys}", job_type=job_type)
for key in keys:
if callback_list := callbacks.get(key):
if isinstance(keys, str):
# Almost all calls to this function use a single key
# so we optimize for that case. We don't use setdefault
# here because this function gets called ~20000 times
# during startup, and we want to avoid the overhead of
# creating empty lists and throwing them away.
if callback_list := callbacks.get(keys):
callback_list.append(job)
else:
callbacks[key] = [job]
callbacks[keys] = [job]
keys = [keys]
else:
for key in keys:
if callback_list := callbacks.get(key):
callback_list.append(job)
else:
callbacks[key] = [job]
return ft.partial(_remove_listener, hass, listeners_key, keys, job, callbacks)