efficiency question

nnorwitz at gmail.com nnorwitz at gmail.com
Sat Jul 1 01:39:51 EDT 2006


Fredrik Lundh wrote:
>
> when in doubt, ask the compiler:
>
> def code(x):
>     if x in ("abc", "def", "xyz"):
>         doStuff()
>     elif x in ("pqr", "tuv", "123"):
>         doOtherStuff()
>
> import dis
> dis.dis(code)
>
> prints:
>
>   2           0 LOAD_FAST                0 (x)
>               3 LOAD_CONST               7 (('abc', 'def', 'xyz'))
...
>
> so the answer is "yes, in this specific case".

Part of the specific case means it's Python 2.4 or later.  In 2.3 it
looks like this:

  2           0 LOAD_GLOBAL              0 (x)
              3 LOAD_CONST               1 ('abc')
              6 LOAD_CONST               2 ('def')
              9 LOAD_CONST               3 ('xyz')
             12 BUILD_TUPLE              3
             15 COMPARE_OP               6 (in)
             18 JUMP_IF_FALSE           11 (to 32)
             21 POP_TOP

so in this case (Python 2.3), the answer is no.

n




More information about the Python-list mailing list