[Python-Dev] dict.addlist()
Jp Calderone
exarkun at intarweb.us
Tue Jan 20 10:10:05 EST 2004
On Tue, Jan 20, 2004 at 09:46:02AM -0500, Jeremy Hylton wrote:
> On Tue, 2004-01-20 at 09:41, Moore, Paul wrote:
> > From: Raymond Hettinger
> > > [Bob Ippolito]
> > >> d.setdefault(k, factory=list).append(v) ?
> > >
> > > That is somewhat nice and backwards compatible too.
> >
> > -1
> >
> > How is it more expressive than d.setdefault(k, []).append(v)? As
> > far as I can see, it's longer and contains an extra obscure(ish)
> > term (factory).
>
> One benefit is that it doesn't create an unnecessary empty list when the
> key is already in the dictionary.
>
This sounds like a benefit if it is faster to not create the empty list?
Naive preliminary testing does not indicate that it is, I imagine due to the
keyword argument overhead. My test functions:
def foo(x, y=None, z=None):
pass
def f1():
for x in xrange(10000000):
foo(10, [])
def f2():
for x in xrange(10000000):
foo(10, z=list)
7.8 and 8.8 seconds to execute, respectively. Since f1 and f2 aren't C
functions, maybe it's not an accurate prediction of how setdefault would
behave... but it does seem that object creation overhead is pretty minimal.
For other cases, where the overhead is much greater, it might be a
different story. My own code shows no examples of that though (actually I
seem to only use setdefault with 2 defaults, None and []).
Jp
More information about the Python-Dev
mailing list