Commit 850a898
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
1 file changed
+8
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
742 | 742 | | |
743 | 743 | | |
744 | 744 | | |
| 745 | + | |
| 746 | + | |
| 747 | + | |
| 748 | + | |
| 749 | + | |
| 750 | + | |
| 751 | + | |
| 752 | + | |
745 | 753 | | |
746 | 754 | | |
747 | 755 | | |
| |||
0 commit comments