Skip to content

Commit 4e67f09

Browse files
committed
More optimization.
- Cache the result of os.path.split(root)[1].lower() (this is *very* costly, relatively speaking). - Cache some more string operations on the Prepared class, and use `__slots__` to speed up attribute access. It would be nice to also use `__slots__` on FastPath, but FastPath relies on being able to overwrite the joinpath method at the instance level and that's not compatible with `__slots__`; moving joinpath to always be on the instance (`self.joinpath = Path(self.root).joinpath`) is slower due to the sometimes unnecessary creation of a Path instance. Overall the new version's runtime (on a previously described benchmark) is around 60% of the original one (i.e. a bit less than 2x speedup).
1 parent bc93d0f commit 4e67f09

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

importlib_metadata/__init__.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,7 @@ class FastPath:
408408

409409
def __init__(self, root):
410410
self.root = root
411+
self._root_n_low = os.path.split(root)[1].lower()
411412

412413
def joinpath(self, child):
413414
return pathlib.Path(self.root, child)
@@ -430,10 +431,9 @@ def zip_children(self):
430431
)
431432

432433
def is_egg(self, search):
433-
root_n_low = os.path.split(self.root)[1].lower()
434-
434+
root_n_low = self._root_n_low
435435
return (
436-
root_n_low == search.normalized + '.egg'
436+
root_n_low == search.versionless_egg_name
437437
or root_n_low.startswith(search.prefix)
438438
and root_n_low.endswith('.egg'))
439439

@@ -452,19 +452,23 @@ class Prepared:
452452
"""
453453
A prepared search for metadata on a possibly-named package.
454454
"""
455-
normalized = ''
456-
prefix = ''
455+
456+
__slots__ = ('name', 'versionless_egg_name', 'prefix', 'exact_matches')
457+
457458
suffixes = '.dist-info', '.egg-info'
458-
exact_matches = [''][:0]
459459

460460
def __init__(self, name):
461461
self.name = name
462462
if name is None:
463+
self.versionless_egg_name = ''
464+
self.prefix = ''
465+
self.exact_matches = []
463466
return
464-
self.normalized = name.lower().replace('-', '_')
465-
self.prefix = self.normalized + '-'
467+
normalized = name.lower().replace('-', '_')
468+
self.versionless_egg_name = normalized + '.egg'
469+
self.prefix = normalized + '-'
466470
self.exact_matches = [
467-
self.normalized + suffix for suffix in self.suffixes]
471+
normalized + suffix for suffix in self.suffixes]
468472

469473

470474
@install

0 commit comments

Comments
 (0)