[Tutor] Efficiency of while versus (x)range

Shane O'Connor spiderbabymass at gmail.com
Thu Mar 17 01:32:29 CET 2011


First-time poster here. I've a question about loop efficiency - I was
wondering whether this code:

i = 0
while i < 1000:
    do something

is more efficient than:

for i in range(1000):
    do something


for i in xrange(1000):
    do something

In my mind, the while loop should not allocate as much memory as range or
have the overhead of the iterator of xrange (although aesthetically, I
prefer the x/range style). Is this the case or does the compiler do
something clever here?

In particular, I'm using Python 2.4.3 on a web server which needs to run as
fast as possible using as little memory as possible (no surprises there!).
I'm aware that there are more significant optimizations than the above and I
will profile the code rather than prematurely optimize loops at the sake of
readability/errors but I'm still curious about the answer.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110316/ae5842aa/attachment.html>

More information about the Tutor mailing list