[Tutor] Re: Re: copies deep and shallow
project5 at redrival.net
Tue Feb 17 14:05:38 EST 2004
Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST):
>> Why would you use a (very slow) deepcopy when it doesn't offer any extra
>> functionality? I can't modify integers/strings/tuples in-place, so I can't
> I see. So deepcopy is slow, even for shallow objects?
Well, if you try deepcopying that list of integers as I wrote in one of the
earlier messages, you'll notice it's very slow compared to a shallow copy.
And things don't get much shallower than integers :).
It's easy to notice that a deepcopy will allocate a truckload of extra
memory, while a shallow copy will allocate a lot less - just keep an eye on
your task manager when doing an extremely large deepcopy. The shallow copy
just kind of says for every part of some large object "this part is the
same part as that one over there", which takes very little time and space
to say. Deepcopy sort of says for every little piece: "Make a new thing
here. Now make it look exactly the same as that piece over there. But it
won't be the same piece." which takes a lot of time and memory.
Reference is even faster because it only does "See this thing here? It's
the same as that very large thing over there." - it doesn't even bother
saying this thing for all the parts of the very large thing.
You can see this very easily like this:
>>> a = [[i] for i in range(50000)] # list of 50000 single item lists
>>> b = copy.deepcopy(a)
>>> c = copy.copy(a)
>>> d = a
>>> id(a), id(b), id(c), id(d) # a and d have the same id (memory address)
(23646544, 23646384, 27999440, 23646544)
>>> id(a), id(b), id(c), id(d)
(23646928, 28001328, 23646928, 23646928)
# all the items have the same memory address, except for the one in b
# which was deepcopied.
>> But generally speaking you can ignore copy if you wish and write perfectly
>> reasonable applications without even knowing it exists :). But then again,
> Yes. This is what I was thinking.
>> you can also ignore deepcopy if you wish, or dictionaries all together
>> (there are plenty of languages without a dictionary type) or...
> But, I'm teaching a python class! I have to deep-understand everything.
> And I love the dictionary type. So much is done for free.
I agree, but even simpler types like lists are also much better than the
old-school arrays found in other languages. Even integers are a lot better
because there's only one kind of them (or two, depending whether you count
the long variety as a separate one) instead of... about five :).
> I'm very grateful that you have taken the time to explain all this.
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor