[Python-Dev] Can LOAD_GLOBAL be optimized to a simple array lookup?

Noam Raphael noamraph at gmail.com
Thu Aug 24 00:50:34 CEST 2006


2006/8/24, Brett Cannon <brett at python.org>:
>
>
>
> On 8/23/06, K.S.Sreeram <sreeram at tachyontech.net> wrote:
> > Hi all,
> >
> > I noticed in Python/ceval.c that LOAD_GLOBAL uses a dictionary lookup,
> > and was wondering if that can be optimized to a simple array lookup.
>
>
> No, not as the language  stands now.
>
> > If i'm right there are 3 kinds of name lookups: locals, outer
> > scopes(closures), and globals. (not counting attribute lookup). Locals
> > are identified by, either the presence of assignments, or their presence
> > in the arg list. So all name lookups can be classified into the 3 types
> > at compile/load time.
> >
> > Since we know, at load time, which names are global.. Can't we simply
> > build a global name table and replace LOAD_GLOBALs with a lookup at the
> > corresponding index into the global name table?
>
>
> But we don't know statically what the globals will be.  You can import a
> module and put something in its global namespace externally.  That is done
> after load time or compile time.
>
I think that it can be implemented for the language as it stands now.
I don't know whether it will be a good thing or not.

In principle, you can add a feature to dict implementation that will
allow it to notify when the value of a specific key changes. If you
have that, you can change LOAD_GLOBAL implementation to:
1. look for the global.
2. ask for notification when the global dict changes in a way that
will change the meaning of the global.
3. change the LOAD_GLOBAL opcode to something like LOAD_CONST, and set
the notification from the dict to update the LOAD_CONST opcode to the
new object.

In that way, LOAD_GLOBAL will cause a dict lookup only once. Changing
the value of globals will require more work, though.

Again, I'm not saying that it's desired, just that it's possible.

Have a good day,
Noam


More information about the Python-Dev mailing list