Em Qua, 2006-04-12 às 11:36 +1000, Steven D'Aprano escreveu: > On Tue, 11 Apr 2006 19:15:18 +0200, Martin v. Löwis wrote: > > > Felipe Almeida Lessa wrote: > >> I love benchmarks, so as I was testing the options, I saw something very > >> strange: > >> > >> $ python2.4 -mtimeit 'x = range(100000); ' > >> 100 loops, best of 3: 6.7 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); del x[:]' > >> 100 loops, best of 3: 6.35 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); x[:] = []' > >> 100 loops, best of 3: 6.36 msec per loop > >> $ python2.4 -mtimeit 'x = range(100000); del x' > >> 100 loops, best of 3: 6.46 msec per loop > >> > >> Why the first benchmark is the slowest? I don't get it... could someone > >> test this, too? > > > > In the first benchmark, you need space for two lists: the old one and > > the new one; > > Er, what new list? I see only one list, x = range(100000), which is merely > created then nothing done to it. Have I missed something?
He's talking about the garbage collector. Talking about the GC, do you want to see something *really* odd? $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); ' 100 loops, best of 3: 13 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); del x[:]' 100 loops, best of 3: 8.19 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); x[:] = []' 100 loops, best of 3: 8.16 msec per loop $ python2.4 -mtimeit -s 'from gc import collect' 'collect(); x = range(100000); del x' 100 loops, best of 3: 8.3 msec per loop But in this case I got the answer (I think): - When you explicitly delete the objects, the GC already know that it can be collected, so it just throw the objects away. - When we let the "x" variable continue to survive, the GC has to look at all the 100001 objects to see if they can be collected -- just to see that it can't. Also, IIRC "del x" is slower than "x = []" because removing a name from the namespace is more expensive than just assigning something else to it. Right? > I understood Felipe to be asking, why does it take longer to just create a > list, than it takes to create a list AND then do something to it? I see dead people... ;-) -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list