mirror of
https://github.com/python/cpython.git
synced 2025-07-07 19:35:27 +00:00
gh-128118: Speed up copy.copy with fast lookup for atomic and container types (#128119)
This commit is contained in:
parent
3480124321
commit
34b85ef26c
2 changed files with 11 additions and 18 deletions
27
Lib/copy.py
27
Lib/copy.py
|
@ -67,13 +67,15 @@ def copy(x):
|
||||||
|
|
||||||
cls = type(x)
|
cls = type(x)
|
||||||
|
|
||||||
copier = _copy_dispatch.get(cls)
|
if cls in _copy_atomic_types:
|
||||||
if copier:
|
return x
|
||||||
return copier(x)
|
if cls in _copy_builtin_containers:
|
||||||
|
return cls.copy(x)
|
||||||
|
|
||||||
|
|
||||||
if issubclass(cls, type):
|
if issubclass(cls, type):
|
||||||
# treat it as a regular class:
|
# treat it as a regular class:
|
||||||
return _copy_immutable(x)
|
return x
|
||||||
|
|
||||||
copier = getattr(cls, "__copy__", None)
|
copier = getattr(cls, "__copy__", None)
|
||||||
if copier is not None:
|
if copier is not None:
|
||||||
|
@ -98,23 +100,12 @@ def copy(x):
|
||||||
return _reconstruct(x, None, *rv)
|
return _reconstruct(x, None, *rv)
|
||||||
|
|
||||||
|
|
||||||
_copy_dispatch = d = {}
|
_copy_atomic_types = {types.NoneType, int, float, bool, complex, str, tuple,
|
||||||
|
|
||||||
def _copy_immutable(x):
|
|
||||||
return x
|
|
||||||
for t in (types.NoneType, int, float, bool, complex, str, tuple,
|
|
||||||
bytes, frozenset, type, range, slice, property,
|
bytes, frozenset, type, range, slice, property,
|
||||||
types.BuiltinFunctionType, types.EllipsisType,
|
types.BuiltinFunctionType, types.EllipsisType,
|
||||||
types.NotImplementedType, types.FunctionType, types.CodeType,
|
types.NotImplementedType, types.FunctionType, types.CodeType,
|
||||||
weakref.ref, super):
|
weakref.ref, super}
|
||||||
d[t] = _copy_immutable
|
_copy_builtin_containers = {list, dict, set, bytearray}
|
||||||
|
|
||||||
d[list] = list.copy
|
|
||||||
d[dict] = dict.copy
|
|
||||||
d[set] = set.copy
|
|
||||||
d[bytearray] = bytearray.copy
|
|
||||||
|
|
||||||
del d, t
|
|
||||||
|
|
||||||
def deepcopy(x, memo=None, _nil=[]):
|
def deepcopy(x, memo=None, _nil=[]):
|
||||||
"""Deep copy operation on arbitrary Python objects.
|
"""Deep copy operation on arbitrary Python objects.
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
Improve performance of :func:`copy.copy` by 30% via
|
||||||
|
a fast path for atomic types and container types.
|
Loading…
Add table
Add a link
Reference in a new issue