The difference is that STORE_FAST is faster (!) than STORE_NAME . 區別在於STORE_FAST (!)比STORE_NAME更快(!)。 This is because in a function, i is a local but at toplevel it is a global. 這是因為在函式中, i是區域性變數,但在頂層是全域性變數。
To examine bytecode, use the dis module . 要檢查位元組碼,請使用dis模組 。 I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin . 我可以直接反彙編該函式,但是要反彙編頂層程式碼,我必須使用compile Builtin 。
Inside a function, the bytecode is 在函式內部,位元組碼為
2 0 SETUP_LOOP 20 (to 23)
3 LOAD_GLOBAL 0 (xrange)
6 LOAD_CONST 3 (100000000)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 6 (to 22)
16 STORE_FAST 0 (i)
3 19 JUMP_ABSOLUTE 13
>> 22 POP_BLOCK
>> 23 LOAD_CONST 0 (None)
26 RETURN_VALUE
At top level, the bytecode is 在頂層,位元組碼是
1 0 SETUP_LOOP 20 (to 23)
3 LOAD_NAME 0 (xrange)
6 LOAD_CONST 3 (100000000)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 6 (to 22)
16 STORE_NAME 1 (i)
2 19 JUMP_ABSOLUTE 13
>> 22 POP_BLOCK
>> 23 LOAD_CONST 2 (None)
26 RETURN_VALUE
The difference is that STORE_FAST is faster (!) than STORE_NAME . 區別在於STORE_FAST (!)比STORE_NAME更快(!)。 This is because in a function, i is a local but at toplevel it is a global. 這是因為在函式中, i是區域性變數,但在頂層是全域性變數。
To examine bytecode, use the dis module . 要檢查位元組碼,請使用dis模組 。 I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin . 我可以直接反彙編該函式,但是要反彙編頂層程式碼,我必須使用compile Builtin 。