why simple for loop with if condition is faster than conditional generator expression in python

大兔子大兔子 提交于 2019-12-25 15:51:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!