2010/12/28 Lukas Lueg <span dir="ltr">&lt;<a href="mailto:lukas.lueg@googlemail.com">lukas.lueg@googlemail.com</a>&gt;</span><br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
Consider the following code:<br>
<br>
def foobar(x):<br>
    for i in range(5):<br>
        x[i] = i<br>
<br>
The bytecode in python 2.7 is the following:<br>
<br>
  2           0 SETUP_LOOP              30 (to 33)<br>
              3 LOAD_GLOBAL              0 (range)<br>
              6 LOAD_CONST               1 (5)<br>
              9 CALL_FUNCTION            1<br>
             12 GET_ITER<br>
        &gt;&gt;   13 FOR_ITER                16 (to 32)<br>
             16 STORE_FAST               1 (i)<br>
<br>
  3          19 LOAD_FAST                1 (i)<br>
             22 LOAD_FAST                0 (x)<br>
             25 LOAD_FAST                1 (i)<br>
             28 STORE_SUBSCR<br>
             29 JUMP_ABSOLUTE           13<br>
        &gt;&gt;   32 POP_BLOCK<br>
        &gt;&gt;   33 LOAD_CONST               0 (None)<br>
             36 RETURN_VALUE<br>
<br>
Can&#39;t we optimize the LOAD_FAST in lines 19 and 25 to a single load<br>
and put the reference twice on the stack? There is no way that the<br>
reference of i might change in between the two lines. Also, the<br>
load_fast in lne 22 to reference x could be taken out of the loop as x<br> will always point to the same object....</blockquote><div><br></div><div>Yes, you can, but you need:</div><div>- a better AST evaluator (to mark symbols/variables with proper attributes);</div>
<div>- a better optimizer (usually located on compile.c) which has a &quot;global vision&quot; (not limited to single instructions and/or single expressions).</div><div><br></div><div>It&#39;s not that simple, and the results aren&#39;t guaranteed to be good.</div>
<div><br></div><div>Also, consider that Python, as a dynamic-and-not-statically-compiled language need to find a good trade-off between compilation time and execution.</div><div><br></div><div>Just to be clear, a C program is usually compiled once, then executed, so you can spend even *hours* to better optimize the final binary code.</div>
<div><br></div><div>With a dynamic language, usually the code is compiled and the executed as needed, in &quot;realtime&quot;. So it isn&#39;t practical neither desirable having to wait too much time before execution begins (the &quot;startup&quot; problem).</div>
<div><br></div><div>Python stays in a &quot;gray area&quot;, because modules are usually compiled once (when they are first used), and executed many times, but it isn&#39;t the only case.</div><div><br></div><div>You cannot assume that optimization techniques used on other (static) languages can be used/ported in Python.</div>
<div><br></div><div>Cesare</div>