The problem in your code is the range
function. In Python 2, it creates a list. For large lists like the ones in your benchmarks, this becomes a problem. In Python 3, range
returns a generator. A workaround for Python 2 is to use the xrange
function, which is lazy as well.
As a test, let's create a benchmark function like yours, but using xrange:
def returngenerator2(times):
t = time.time()
g = (i for i in xrange(times))
print "generator2: {}".format(time.time() - t)
return g
And test it:
>>> l = returnlist(10**7)
list: 0.580000162125
>>> g = returngenerator(10**7)
generator: 0.115000009537
>>> x = returngenerator2(10**7)
generator2: 0.0
>>> x2 = returngenerator2(10**8)
generator2: 0.0
>>> x3 = returngenerator2(10**9)
generator2: 0.0
Seems to work. :)