[Python-Dev] performance of {} versus dict(), de fmd(**kw): return kw trumps all ; -)

martin at v.loewis.de martin at v.loewis.de
Thu Nov 15 05:27:23 CET 2012


Zitat von Chris Withers <chris at simplistix.co.uk>:

> $ python2.7 -m timeit -n 1000000 -r 5 -v  
> "{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7}"
> raw times: 1.49 1.49 1.5 1.49 1.48
> 1000000 loops, best of 5: 1.48 usec per loop
>
> $ python2.7 -m timeit -n 1000000 -r 5 -v 'dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7)'
> raw times: 2.35 2.36 2.41 2.42 2.35
> 1000000 loops, best of 5: 2.35 usec per loop
>
> $ python2.7 -m timeit -n 1000000 -r 5 -v 'def md(**kw): return kw;  
> md(a=1,b=2,c=3,d=4,e=5,f=6,g=7)'
> raw times: 0.507 0.515 0.516 0.529 0.524
> 1000000 loops, best of 5: 0.507 usec per loop
>
> For the naive observer (ie: me!), why is that?

It's faster than calling dict() because the dict code will
create a second dictionary, and discard the keywords dictionary.

It's (probably) faster than the dictionary display, because
the {} byte code builds the dictionary one-by-one, whereas
the keywords dictionary is built in a single step (taking
all keys and values from the evaluation stack).

Regards,
Martin




More information about the Python-Dev mailing list