Restore service call performance by avoiding expensive runtime cast (#143378)

Improve service call performance by avoiding expensive runtime type checking

Most of the overhead here was casting
This commit is contained in:
J. Nick Koston 2025-04-21 03:37:10 -10:00 committed by GitHub
parent 7ea8827e69
commit bb73ecc1f4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -21,7 +21,7 @@ from socket import ( # type: ignore[attr-defined] # private, not in typeshed
_GLOBAL_DEFAULT_TIMEOUT,
)
import threading
from typing import Any, cast, overload
from typing import TYPE_CHECKING, Any, cast, overload
from urllib.parse import urlparse
from uuid import UUID
@ -355,7 +355,13 @@ def ensure_list[_T](value: _T | None) -> list[_T] | list[Any]:
"""Wrap value in list if it is not one."""
if value is None:
return []
return cast(list[_T], value) if isinstance(value, list) else [value]
if isinstance(value, list):
if TYPE_CHECKING:
# https://github.com/home-assistant/core/pull/71960
# cast with a type variable is still slow.
return cast(list[_T], value)
return value # type: ignore[unreachable]
return [value]
def entity_id(value: Any) -> str: