|
Re: For Loops
|
Posted: Sep 14, 2005 4:02 AM
|
|
> That's not true, it's actually always better (or so the Python documentation states) to use xrange over range for iterations: marginally better for regular iterations (xrange is minimally faster) but xrange is much more memory-efficient, and also faster when the loop does not end (when you get out through a "break").
Funny. I remember reading a while back that Guido prefered "range" for speed. After looking for it myself in the documentation, I found this:
http://docs.python.org/lib/typesseq-xrange.html
"The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages."
So, for the hell of it, I just ran my own test, and found my results to support the above:
for i in xrange(someBigNumber): for j in range(100): x=1+1
versus
for i in xrange(someBigNumber): for j in xrange(100): x=1+1
I tried 100 here, but I also tried 1 and 10. I found that, on my Pentium running Windows, the difference in time was negligeable (sometimes, range would win, others xrange would win). This combined that it might change from one implementation to the next, my results show that it isn't really worth a debate (ie. I was at fault for mentioning speed in the first place). I would be interested in the results from someone who has tested on 5+ different implementations, if you would happen to know where I could find that. Also, could you point me to where in the documentation you saw that xrange was faster? I was looking, but I couldn't find it.
> What you describe here is not the "iterable" protocol, it's (the main) part of the "generator" protocol.
For some dumb reason, I made the decision to use "iterable" instead of "generator" since I thought, from a C/C++ programmer's perspective, that iterable would be more readily understood. I wasn't being too technical in my reply. This was a lapse of judgement on my part, since I usually will use the vocabulary of the particular language of which I am speaking. I would like to thank you however for pointing this out to me.
Thank you for being thorough. No more will I make a assumptions that I can get away with anything when posting on these Heron forums ;)
|
|