问题
Why is this for loop with if condition in first case is more than 2 times faster than second case with a conditional generator expression?
%%timeit
for i in range(100000):
if i < 10000:
continue
pass
clocks at 100 loops, best of 3: 2.85 ms per loop, while using generator expression:
%%timeit
for i in (i for i in range(100000) if i >= 10000):
pass
100 loops, best of 3: 6.03 ms per loop
回答1:
First version: For each element in range: assign it to i.
Second version: For each element in range: assign it to inner i (third one from the left), evaluate expression i (the i from ...(i for... assign result to "outer" (leftmost) i.
The if statements have probably a similar performance impact in both versions.
来源:https://stackoverflow.com/questions/46209173/why-simple-for-loop-with-if-condition-is-faster-than-conditional-generator-expre