list.clear() missing?!?

Raymond Hettinger python at rcn.com
Wed Apr 12 15:55:40 EDT 2006


[Felipe Almeida Lessa]
> > 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?

[Dan Christensen]
> I get similar behaviour.  No idea why.

It is an effect of the memory allocator and fragmentation.  The first
builds up a list with increasingly larger sizes.  It periodically
cannot grow in-place because something is in the way (some other
object) so it needs to move its current entries to another, larger
block and grow from there.  In contrast, the other entries are reusing
a the previously cleared out large block.

Just for grins, replace the first with"
  'x=None; x=range(100000)'
The assignment to None frees the reference to the previous list and
allows it to be cleared so that its space is immediately available to
the new list being formed by range().




More information about the Python-list mailing list