[Python-Dev] performance of {} versus dict()
Chris Withers
chris at simplistix.co.uk
Wed Nov 14 10:12:05 CET 2012
Hi All,
A colleague pointed me at Doug's excellent article here:
http://www.doughellmann.com/articles/misc/dict-performance/index.html
...which made me a little sad, I suspect I'm not the only one who finds:
a_dict = dict(
x = 1,
y = 2,
z = 3,
...
)
...easier to read than:
a_dict = {
'x':1,
'y':2,
'z':3,
...
}
What can we do to speed up the former case?
Here's comparison for different versions of CPython:
$ python2.5 -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.96 2.49 2.47 2.42 2.42
1000000 loops, best of 5: 2.42 usec per loop
$ python2.5 -m timeit -n 1000000 -r 5 -v
"{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7}"
raw times: 1.69 1.71 1.68 1.68 1.68
1000000 loops, best of 5: 1.68 usec per loop
$ python2.6 -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.41 2.41 2.42 2.44 2.41
1000000 loops, best of 5: 2.41 usec per loop
$ python2.6 -m timeit -n 1000000 -r 5 -v
"{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7}"
raw times: 1.51 1.51 1.52 1.51 1.51
1000000 loops, best of 5: 1.51 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.32 2.31 2.31 2.32 2.31
1000000 loops, best of 5: 2.31 usec per loop
$ 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.77 1.76 1.55
1000000 loops, best of 5: 1.49 usec per loop
So, not the 6 times headline figure that Doug quotes, but certainly a
difference. Can someone with Python 3 handy compare there too?
cheers,
Chris
--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
More information about the Python-Dev
mailing list