Optimising literals away

MRAB python at mrabarnett.plus.com
Tue Aug 31 17:53:50 EDT 2010


On 31/08/2010 21:18, Terry Reedy wrote:
> 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.
>
There's still the possibility of some optimisation. If the resulting
set is never stored anywhere (bound to a name, for example) then it
could be created once. When the expression is evaluated there could be
a check so see whether 'set' is bound to the built-in class, and, if it
is, then just use the pre-created set.

>>> 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.
>



More information about the Python-list mailing list