[Tutor] loop performance in global namespace (python-2.6.1)
Kent Johnson
kent37 at tds.net
Thu Mar 12 17:37:15 CET 2009
On Thu, Mar 12, 2009 at 11:41 AM, spir <denis.spir at free.fr> wrote:
> Le Thu, 12 Mar 2009 11:13:33 -0400,
> Kent Johnson <kent37 at tds.net> s'exprima ainsi:
>
>> Because local name lookup is faster than global name lookup. Local
>> variables are stored in an array in the stack frame and accessed by
>> index. Global names are stored in a dict and accessed with dict access
>> (dict.__getitem__()).
>
> ? I thought this was mainly because a name has first to be searched (unsuccessfully) locally before a global lookup is launched.
I'm pretty sure, local names are hard-coded to the stack frame.
Non-local names must follow the lookup sequence (containing scope),
(global scope), (builtins).
> Also, are locals really stored in an array? How does lookup then proceed? Is it a kind of (name,ref) sequence?
Yes, they are really stored in an array. A reference from GvR himself:
"The Python "compiler" optimizes most function bodies so that for
local variables, no dictionary lookup is necessary, but a simple array
indexing operation is sufficient."
http://www.python.org/doc/essays/list2str.html
Local variables are accessed using the LOAD_FAST and STORE_FAST
opcodes. From http://docs.python.org/library/dis.html:
LOAD_FAST(var_num)¶
Pushes a reference to the local co_varnames[var_num] onto the stack.
STORE_FAST(var_num)¶
Stores Top Of Stack into the local co_varnames[var_num].
Looking at the OP's code:
In [1]: def f1():
...: counter = 0
...: while counter < limit:
...: counter += 1
In [2]:
In [3]: import dis
In [4]: dis.dis(f1)
3 0 LOAD_CONST 1 (0)
3 STORE_FAST 0 (counter)
4 6 SETUP_LOOP 28 (to 37)
>> 9 LOAD_FAST 0 (counter)
12 LOAD_GLOBAL 0 (limit)
15 COMPARE_OP 0 (<)
18 JUMP_IF_FALSE 14 (to 35)
21 POP_TOP
5 22 LOAD_FAST 0 (counter)
25 LOAD_CONST 2 (1)
28 INPLACE_ADD
29 STORE_FAST 0 (counter)
32 JUMP_ABSOLUTE 9
>> 35 POP_TOP
36 POP_BLOCK
>> 37 LOAD_CONST 0 (None)
40 RETURN_VALUE
Kent
More information about the Tutor
mailing list