python - Are compound if statements faster, or multiple if statements? -


say have 2 pieces of code:

if foo == true , bar == false , baz == true:     

and

if foo == true:     if bar == false:         if baz == true:             

which faster?

on machine ipython

in [1]: foo = true in [2]: bar = false in [3]: baz = true  in [4]: %%timeit    ...: if foo , not bar , baz:    ...:     lambda: none 1000000 loops, best of 3: 265 ns per loop  in [5]: %%timeit    ...: if foo:    ...:   if not bar:    ...:     if baz:    ...:       lambda: none 1000000 loops, best of 3: 275 ns per loop 

it looks there whopping 10ns overhead if split up. if 10ns matters, should using language.

so practical purposes, no, there no difference.

if little deeper, can see tiny difference comes though.

in [6]: def compound():    ...:     if foo , not bar , baz:    ...:         lambda: none in [7]: def multiple():    ....:     if foo:    ....:         if not bar:    ....:             if baz:    ....:                 lambda: none  in [8]: import dis in [9]: dis.dis(compound)   2           0 load_global              0 (foo)               3 pop_jump_if_false       29               6 load_global              1 (bar)               9 unary_not                         10 pop_jump_if_false       29              13 load_global              2 (baz)              16 pop_jump_if_false       29    3          19 load_const               1 (<code object <lambda> @ 0x101d953b0, file "<ipython-input-9-d057c552d038>", line 3>)              22 make_function            0              25 pop_top                           26 jump_forward             0 (to 29)         >>   29 load_const               0 (none)              32 return_value    

this has 13 instructions

in [15]: dis.dis(g)   2           0 load_global              0 (foo)               3 pop_jump_if_false       34    3           6 load_global              1 (bar)               9 pop_jump_if_true        34    4          12 load_global              2 (baz)              15 pop_jump_if_false       31    5          18 load_const               1 (<code object <lambda> @ 0x101dbb530, file "<ipython-input-10-32b41e5f6f2b>", line 5>)              21 make_function            0              24 pop_top                           25 jump_absolute           31              28 jump_absolute           34         >>   31 jump_forward             0 (to 34)         >>   34 load_const               0 (none)              37 return_value   

this has 14 instructions.

i did default ipython on system, 2.7.5 @ moment, can use technique profile pretty want version of python happen running.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -