switowski / writing-faster-python3

Code examples for the writing faster Python 3 talk
MIT License
55 stars 3 forks source link

any.py #1

Open Alex-CodeLab opened 1 year ago

Alex-CodeLab commented 1 year ago

Hi, I think the reason you give in https://github.com/switowski/writing-faster-python3/blob/main/any.py is not correct, it is not because of list construction overhead, but because the 'or' function stops when something is True.

Speed is the same if all variables are '0' : a,b,c,d,e,f = 0,0,0,0,0,0 or a,b,c,d,e,f = 0,0,0,0,0,1

-- However, there is another interesting situation: defining the list outside the function does seem to be faster (in some situations):

x = [a, b, c, d, f]
def test_any():
   return 1 if any(x) else 0
switowski commented 1 year ago

Hi Alex,

Thanks for the comment. You are right. I did a terrible job with this example, so I checked other scenarios (with all items being 0s or 1s and with the first vs. last element being 1), plus created the list outside of the benchmark's code.

Thanks for pointing this out!