I'm missing something here with range vs. xrange

Joe Goldthwaite joe at goldthwaites.com
Fri Dec 7 21:58:57 EST 2007


>You can't imagine why someone might prefer an iterative solution over
>a greedy one? Depending on the conditions, the cost of creating the
>list can be a greater or a lesser part of the total time spent. Actual
>iteration is essentially the same cost for both. Try looking at memory
>usage while you're running these tests.

I can imagine why someone would want to use in iterative solution.  What I
don't understand is why there's so little difference between the two.
Here's what I think is going on;

To do a range(1000000)

	1. Allocate a big chunk of memory
	2. Fill the memory with the range of integers
	3. Setup an index into the memory array
	4. Every time the program asks for the next item, bump
	   the memory index by one, get the value and return it.

To do an xrange(10000000)

	1. Set up a counter
	2. Every time the program asks for the next item, increment
         the counter and return it.

I guess I thought that between these two methods, the second would be
dramatically faster. An order of magnitude faster.  My surprise is that it's
not.  That's why I figured I'm missing something because the above steps
don't seem to describe what's going on.  Hence, the title, "I'm missing
something".




More information about the Python-list mailing list