擅长:python、mysql、java
<p>在我的机器上,遍历生成器比遍历列表慢:</p>
<pre><code>from timeit import timeit
# just for simulation
def distance(la, lb):
return abs(la-lb)
# for simulation, too
def route():
return xrange(10000)
# the longer(code) and faster but wasteful(memory) way
def longer_faster_wasteful():
return sum([distance(location, location+1) for location in route()])
# the shorter(code) and saving(memory) but slower way
def shorter_slower_saving():
return sum(distance(location, location+1) for location in route())
# print 2.01163072818 on my machine
print timeit(longer_faster_wasteful, number=100)
# print 2.91834802689 on my machine
print timeit(shorter_slower_saving, number=100)
</code></pre>