[CentralOH] Syntactic Sugar (or sacharine)?

Eric Floehr eric at intellovations.com
Fri Aug 12 19:34:41 CEST 2011


> An interesting hypothesis!  You should run a test with the "timeit"
> module to see whether it is truly faster.
> My guess is that it is *not* actually faster, because all of the strings
> that appear as literals in your Python code are "interned" strings - no
> matter how many times the literal string 'min' appears in your program,
> CPython creates only a single string object that gets used over and
> over.  And interned strings are, like functions, compared by identity -
> the check for d['min'] will, just like d[min], be reduced immediately to
> an extremely fast pointer comparison operation.

So I would think there are two drivers for time: hash generation and
hash lookup.  I don't know function object hashes work, but I believe
that string hashes are cached, and as you mentioned, strings are
immutable in Python.

So I ran some timeit tests, and consistently the function key lookup
is slower than the string key lookup:

>>> timeit.Timer("d['min']", "d = { min: 1, 'min': 2 }").timeit(100000000)
>>> timeit.Timer("d[min]", "d = { min: 1, 'min': 2 }").timeit(100000000)

The situation isn't much different for locally created classes:

timeit.Timer("d[Timer]", "d = { Timer: 1, 'min': 2 }").timeit(100000000)

My guess as to the reason is that you have *more* steps in a class or
function hash lookup.  You first have to take the name, find it in the
local scope, then lookup the __hash__ function on the object, and then
make a call to the __hash__() function on the object.  Whereas with a
string, because they are special and highly optimized, you just do a
lookup on the string table and get the hash, without the need for a
function lookup and function call.

Not that any of this matters unless you are in a tight loop with 100's
of millions of lookups, but it's fun to ponder.


> But run timeit anyway, because I could be wrong! :)
> --
> Brandon Craig Rhodes   brandon at rhodesmill.org   http://rhodesmill.org/brandon
> _______________________________________________
> CentralOH mailing list
> CentralOH at python.org
> http://mail.python.org/mailman/listinfo/centraloh

More information about the CentralOH mailing list