Optimising literals away

Arnaud Delobelle arnodel at googlemail.com
Mon Aug 30 12:02:37 EDT 2010


Tobias Weber <towb at gmx.net> writes:

> Hi,
> whenever I type an "object literal" I'm unsure what optimisation will do 
> to it.
>
> def m(arg):
>   if arg & set([1,2,3]):
>     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?
>
> Also I never profiled the regular expression cache...

the dis module can help you for these:

>>> import dis
>>> def m(arg):
...   if arg & set([1,2,3]):
...     return 4
... 
>>> dis.dis(m)
  2           0 LOAD_FAST                0 (arg)
              3 LOAD_GLOBAL              0 (set)
              6 LOAD_CONST               1 (1)
              9 LOAD_CONST               2 (2)
             12 LOAD_CONST               3 (3)
             15 BUILD_LIST               3
             18 CALL_FUNCTION            1
             21 BINARY_AND          
             22 JUMP_IF_FALSE            5 (to 30)
             25 POP_TOP             

  3          26 LOAD_CONST               4 (4)
             29 RETURN_VALUE        
        >>   30 POP_TOP             
             31 LOAD_CONST               0 (None)
             34 RETURN_VALUE        

As you can see, the list literal is built every time the function code
is executed.

-- 
Arnaud



More information about the Python-list mailing list