%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 deepcopyis 15 times slower than copy?
Each function must iterate over the elements of a tuple. During this iteration, copycreates another reference to each element; deepcopyDeepens each element.
But each element is int, and deepcopying a intsimply creates another link to it. In other words, both functions seem to perform exactly the same steps, as many times.
This confirms 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
source
share