Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy.copy vs copy.deepcopy performance on tuples

%python -m timeit -s "import copy" "x = (1, 2, 3)" "copy.deepcopy(x)"
100000 loops, best of 3: 10.1 usec per loop

%python -m timeit -s "import copy" "x = (1, 2, 3)" "copy.copy(x)"
1000000 loops, best of 3: 0.609 usec per loop

Why is deepcopy 15 times slower than copy?

Each function has to iterate through the elements of the tuple. During that iteration, copy creates another reference to each element; deepcopy deepcopies each element.

But each element is an int, and deepcopying an int simply creates another reference to it. In other words, the two functions seem to perform precisely the same steps, the same number of times.

Here's the verification that no new instances are created in the process:

ActivePython 3.2.1.2 (ActiveState Software Inc.) based on
Python 3.2.1 (default, Jul 18 2011, 14:31:09) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = (1,2,3)
>>> import copy
>>> y = copy.copy(x)
>>> z = copy.deepcopy(x)
>>> x is y
True
>>> x is z
True
>>> x[1] is z[1]
True
like image 678
max Avatar asked Apr 22 '12 19:04

max


People also ask

What is the difference between copy copy () and copy Deepcopy ()?

copy() create reference to original object. If you change copied object - you change the original object. . deepcopy() creates new object and does real copying of original object to new one. Changing new deepcopied object doesn't affect original object.

Is Deepcopy slow in Python?

deepcopy() is extremely slow. New! Save questions or answers and organize your favorite content. Learn more.

Is Deep copy faster than shallow copy?

Shallow Copy stores the copy of the original object and points the references to the objects. Deep copy stores the copy of the original object and recursively copies the objects as well. Shallow copy is faster. Deep copy is comparatively slower.

Is Copy () A shallow copy?

The copy. copy() function creates shallow copies of objects.


1 Answers

Tuples are immutable, but they can contain mutable elements:

>>> a = (1, 2, [])
>>> a[2].append(1000)
>>> a
(1, 2, [1000])

Note that the tuple doesn't change: it's the list the one that does; the tuple still contains the exact same list.

deepcopy should recurse copying those mutable elements. copy just copies the references to them.

>>> from copy import copy, deepcopy

>>> a = (1, 2, [])
>>> c = copy(a)
>>> d = deepcopy(a)

>>> a[2].append(1000)

>>> c
(1, 2, [1000])
>>> d
(1, 2, [])
like image 91
Roberto Bonvallet Avatar answered Sep 19 '22 05:09

Roberto Bonvallet