Skip to content

Commit 1fdfae1

Browse files
authored
Merge pull request astropy#20107 from mhvk/units-cache-converters
PERF: Add cache for some speed-up
2 parents c515467 + c46f63f commit 1fdfae1

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

‎astropy/units/core.py‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@
7171
"raise": "error",
7272
}
7373

74+
_CONVERTER_CACHE = {}
75+
7476

7577
class UnitBase:
7678
"""
@@ -562,18 +564,26 @@ def get_converter(self, other, equivalencies=[]):
562564

563565
def _get_converter(self, other, equivalencies=[]):
564566
# Private function of above that requires other to be a Unit.
565-
# First see if it is just a scaling.
567+
# Check if we have cached this -- we do this only with simple
568+
# scalings, since equivalencies can come and go.
569+
if (converter := _CONVERTER_CACHE.get((self, other))) is not None:
570+
return converter
571+
# If not cached, first see if it is just a scaling.
566572
try:
567573
scale = self._to(other)
568574
except UnitsError:
569575
pass
570576
else:
577+
# Yes, it is a simple scaling.
571578
if scale == 1.0:
572579
# If no conversion is necessary, returns ``unit_scale_converter``
573580
# (which is used as a check in quantity helpers).
574-
return unit_scale_converter
581+
converter = unit_scale_converter
575582
else:
576-
return lambda val: scale * _condition_arg(val)
583+
converter = lambda val: scale * _condition_arg(val)
584+
# Cache the converter before returning it.
585+
_CONVERTER_CACHE[(self, other)] = converter
586+
return converter
577587

578588
# if that doesn't work, maybe we can do it with equivalencies?
579589
try:

0 commit comments

Comments
 (0)