[Python-Dev] performance of {} versus dict()
Terry Reedy
tjreedy at udel.edu
Thu Nov 15 00:47:50 CET 2012
On 11/14/2012 4:12 AM, Chris Withers wrote:
To somewhat paraphrase: '''
I prefer 'dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7)' to
"{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7}".
I am sad that the former takes +-2 times as long to run (in 2.7).
Is the difference about the same in 3.x?
What can we do to speed up the former case?
'''
My responses, trying not to duplicate others.
1. Visual preference depends on the viewer. I prefer the dict display,
perhaps because I am more accustomed to it.
2. The two types of expressions have overlapping but distinct use cases.
This differences include that dict can be wrapped or replaced, while
displays cannot.
3. a) 3.x has dict comprehensions. How do they stack up? b) If one were
really initializing multiple dicts with the same starting items, and one
were really concerned about speed, should one calculate the common base
dict just once and then copy? Win7 64 with 3.3.0:
>>> repeat("dict(a=1, b=2, c=3, d=4, e=5)")
[0.6200045004915467, 0.6212762582470646, 0.6114683222573376]
>>> repeat("{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}")
[0.27170026972208233, 0.2594874604131968, 0.25977058559879584]
>>> repeat("d.copy()", "d={'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}")
[0.25768296004457625, 0.243041299387869, 0.2421860830290825]
>>> repeat("{str(i):i for i in range(10)}")
[4.914327732926495, 4.874041570524014, 4.871596119002334]
>>> repeat("{'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7,
'8':8, '9':9}")
[0.5207065648769458, 0.5000415004344632, 0.49980294978922757]
>>> repeat("d.copy()", "d={'0':0, '1':1, '2':2, '3':3, '4':4, '5':5,
'6':6, '7':7, '8':8, '9':9}")
[0.571671864980317, 0.5516194699132484, 0.5514937389677925]
Assuming no overlooked errors in the above...
a) Dict comprehensions are much slower than calls, which makes the calls
look good by comparison. b) Copying is not worthwhile.
4. There are about 3000 issues on the tracker. Nearly all are worth more
attention than this ;-).
--
Terry Jan Reedy
More information about the Python-Dev
mailing list