Closed
Labels
Description
When parsing and normalizing a path, pathlib calls sys.intern() on the string parts:
Line 273 in 96b392d
| parsed = [sys.intern(str(x)) for x in rel.split(sep) if x and x != '.'] |
I've never been able to establish that this is a worthwhile thing to do. The implementation seems incomplete, because the path normalization only occurs when a user manually initialises a path object, and not in paths generated from path.iterdir(), path.walk(), etc. Drives/roots/anchors aren't interned despite most likely to be shared.
Previous discussion: #112856 (comment)
Activity
barneygale commentedon May 24, 2024
CC @pitrou
pitrou commentedon May 28, 2024
That's a good question. The contention is that, if you keep a lot of related paths in memory, interning the path components would yield significant memory savings. But how useful it is would depend on the use case; and it's probably possible to construct use cases where it would be detrimental.
barneygale commentedon May 28, 2024
Thank you :)
Surprisingly,
sys.intern(str(x))accounts for ~10% of the cost ofstr(Path('foo', 'bar'))on my machine. i.e. this patch makes it ~10% faster:pitrou commentedon May 28, 2024
It can probably be micro-optimized if you really care. For example I'm not sure the
strcall is still useful.barneygale commentedon May 28, 2024
Hum! That change used to trip up the
test_str_subclass*tests, but it doesn't any more. I wonder if there's been a change in how string subclasses work elsewhere in the language.vstinner commentedon Jun 3, 2024
Can pathlib have its own "interned strings" cache with a limit on the cache size? Well, I don't know if it's worth it :-)
Pseudo-code with a limit on 3 entries:
Can pathlib remove entries from such cache?
pythonGH-119518: Stop interning strings in pathlib
pythonGH-119518: Stop interning strings in pathlib
GH-119518: Stop interning strings in pathlib GH-123356)