Skip to content

Commit 850a898

Browse files
committed
Make environ.clear() asymptotically efficient (O(N^2) -> O(N)).
The implicit implementation of environ.clear() is MutableMapping.clear(), which calls iter(self) in a loop, once per deleted key. But because iter(self) for environ creates a snapshot of all keys, this results in O(N^2) complexity for environ.clear(). This problem is especially evident on large environments. On my M3 MacBook Pro, it takes 500ms to clear an environment with only 10K variables. A more extreme example: 100K variables take 23s to clear. Environments with thousands of environment variables are rare, but they do exist. The new implementation avoids creating a snapshot of the keys on each iteration, and instead repeatedly tries to delete keys until the environment is empty. This mirrors the current behavior of environ.clear(), while being more efficient asymptotically. Further improvement on Linux/FreeBSD could be achieved by using clearenv() which is part of the standard C library.
1 parent f39dea3 commit 850a898

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

Lib/os.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,14 @@ def __repr__(self):
742742
)
743743
return f"environ({{{formatted_items}}})"
744744

745+
def clear(self):
746+
while self._data:
747+
for key in list(self._data):
748+
try:
749+
del self[key]
750+
except KeyError:
751+
pass
752+
745753
def copy(self):
746754
return dict(self)
747755

0 commit comments

Comments
 (0)