]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-128118: Speed up copy.copy with fast lookup for atomic and container types (#128119)
authorPieter Eendebak <pieter.eendebak@gmail.com>
Mon, 30 Dec 2024 17:18:42 +0000 (18:18 +0100)
committerGitHub <noreply@github.com>
Mon, 30 Dec 2024 17:18:42 +0000 (18:18 +0100)
Lib/copy.py
Misc/NEWS.d/next/Library/2024-12-20-10-57-10.gh-issue-128118.mYak8i.rst [new file with mode: 0644]

index f27e109973cfb728bdd741cc736156328a62cfc0..c64fc0761793f54847882d46a4368e3f34690592 100644 (file)
@@ -67,13 +67,15 @@ def copy(x):
 
     cls = type(x)
 
-    copier = _copy_dispatch.get(cls)
-    if copier:
-        return copier(x)
+    if cls in _copy_atomic_types:
+        return x
+    if cls in _copy_builtin_containers:
+        return cls.copy(x)
+
 
     if issubclass(cls, type):
         # treat it as a regular class:
-        return _copy_immutable(x)
+        return x
 
     copier = getattr(cls, "__copy__", None)
     if copier is not None:
@@ -98,23 +100,12 @@ def copy(x):
     return _reconstruct(x, None, *rv)
 
 
-_copy_dispatch = d = {}
-
-def _copy_immutable(x):
-    return x
-for t in (types.NoneType, int, float, bool, complex, str, tuple,
+_copy_atomic_types = {types.NoneType, int, float, bool, complex, str, tuple,
           bytes, frozenset, type, range, slice, property,
           types.BuiltinFunctionType, types.EllipsisType,
           types.NotImplementedType, types.FunctionType, types.CodeType,
-          weakref.ref, super):
-    d[t] = _copy_immutable
-
-d[list] = list.copy
-d[dict] = dict.copy
-d[set] = set.copy
-d[bytearray] = bytearray.copy
-
-del d, t
+          weakref.ref, super}
+_copy_builtin_containers = {list, dict, set, bytearray}
 
 def deepcopy(x, memo=None, _nil=[]):
     """Deep copy operation on arbitrary Python objects.
diff --git a/Misc/NEWS.d/next/Library/2024-12-20-10-57-10.gh-issue-128118.mYak8i.rst b/Misc/NEWS.d/next/Library/2024-12-20-10-57-10.gh-issue-128118.mYak8i.rst
new file mode 100644 (file)
index 0000000..bc2898e
--- /dev/null
@@ -0,0 +1,2 @@
+Improve performance of :func:`copy.copy` by 30% via
+a fast path for atomic types and container types.