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

Why is this for a cycle with an if condition in the first case more than 2 times faster than the second case with a conditional expression of the generator?

%%timeit for i in range(100000): if i < 10000: continue pass 

on 100 loops, best of 3: 2.85 ms per cycle, using the generator expression:

 %%timeit for i in (i for i in range(100000) if i >= 10000): pass 

100 cycles, best of 3: 6.03 ms per cycle

0
source share
1 answer

First version . For each item in the range: assign it i .

The second version . For each element in the range: assign it to the inner i (third from the left), evaluate the expression i (the result is i from ...(i for... to the "outer" (leftmost) i .

if probably have the same performance impact in both versions.

+1
source

Source: https://habr.com/ru/post/1276193/


All Articles