Thursday, 5 September 2013

Speed difference between iterating over generators and lists

Speed difference between iterating over generators and lists

In the following trivial examples there are two functions that sort a list
of random numbers. The first method passes sorted a generator expression,
the second method creates a list first:
import random
l = [int(1000*random.random()) for i in xrange(10*6)]
def sort_with_generator():
return sorted(a for a in l)
def sort_with_list():
return sorted([a for a in l])
Benchmarking with line profiler indicates that the second option
(sort_with_list) is about twice as fast as the generator expression.
Can anyone explain what's happening, and why the first method is so much
slower than the second?

No comments:

Post a Comment