Assignment saves time?

rpglover64 at gmail.com rpglover64 at gmail.com
Fri Feb 15 05:37:26 EST 2008


In timing my code, which I probably screwed up, I found something
curious:
given that li=range(1000),

the code block (enclosed in braces for clarification)
{
  size=len(li)
  size==1000
}
runs slightly faster than
{
  len(li)==1000
}

I tested this using the timeit module, and though the difference was
small, I would have expected the first code block to do slightly
worse, because it has to assign the length to a variable and then call
the variable (still having to compute the length and having either one
or two additional operations to perform).

I would appreciate it if more knowledgeable coders could
a) point out why I'm wrong and show me how to test it correctly. or
b) explain why this occurs in terminology understandable to someone
who knows next to nothing about the internal workings of python.

I highly appreciate your any response I may receive.  Thank you in
advance.



More information about the Python-list mailing list