Optimising literals away

Terry Reedy tjreedy at udel.edu
Tue Aug 31 22:18:13 CEST 2010


On 8/31/2010 12:33 PM, Aleksey wrote:
> On Aug 30, 10:38 pm, Tobias Weber<t... at gmx.net>  wrote:
>> Hi,
>> whenever I type an "object literal" I'm unsure what optimisation will do
>> to it.

Optimizations are generally implentation dependent. CPython currently 
creates numbers, strings, and tuple literals just once. Mutable literals 
must be created each time as they may be bound and saved.

>> def m(arg):
>>    if arg&  set([1,2,3]):

set() is a function call, not a literal. When m is called, who knows 
what 'set' will be bound to? In Py3, at least, you could write {1,2,3}, 
which is much faster as it avoids creating and deleting a list. On my 
machine, .35 versus .88 usec. Even then, it must be calculated each time 
because sets are mutable and could be returned to the calling code.

>>      return 4
>>
>> Is the set created every time the method is called? What about a
>> frozenset? Or tuple vs list? After how many calls per second does it pay
>> to save it at the module level? Would anybody else find this ugly?

Defining module level constants is considered good practice in some 
circles, especially if is something you might want to change. That is 
what function definitions are (as long as the name is not redefined. 
This is different from having lots of module level variables.

To see what CPython does, you can use the dis module.

-- 
Terry Jan Reedy




More information about the Python-list mailing list