[Python-Dev] performance of {} versus dict(), de fmd(**kw): return kw trumps all ; -)
Terry Reedy
tjreedy at udel.edu
Thu Nov 15 17:21:53 CET 2012
On 11/15/2012 9:58 AM, Stefan Behnel wrote:
> Greg Ewing, 15.11.2012 11:48:
>> martin at v.loewis.de wrote:
>>> It's faster than calling dict() because the dict code will
>>> create a second dictionary, and discard the keywords dictionary.
>>
>> Perhaps in the case where dict() is called with keyword
>> args only, it could just return the passed-in keyword
>> dictionary instead of creating another one?
>
> This should work as long as this still creates a copy of d at some point:
>
> d = {...}
> dict(**d)
I was thinking that CPython could check the ref count of the input
keyword dict to determine whether it is newly created and can be
returned or is pre-existing and must be copied. But it seems not so.
>>> def d(**x): return sys.getrefcount(x)
>>> import sys
>>> d(a = 3)
2
>>> d(**{'a': 3})
2
>>> b = {'a': 3}
>>> d(**b)
2
I was expecting 3 for the last one.
--
Terry Jan Reedy
More information about the Python-Dev
mailing list