What's faster, a==2==b
, or a==2
and b==2
?
To be clear, expression one evaluates both of the items once, and does not compare a
to b
.
And this is worth a read: In Python, is an "and" statement or all() faster?
Timing both methods with timeit
.
I'm using len()
to gauge the execution time better, as a way to delay immediate evaluation.
Setup string for both:
setup = """import random
import string
a = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(2))
b = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(2))"""
Final Test Expression A:
timeit.repeat("len(a)==2==len(b)", setup=setup, repeat=100)
Final Test Expression B:
timeit.repeat("len(a)==2 and len(b)==2", setup=setup, repeat=100)
Both of the tests run the expression one million times, records the time, then does that one hundred times.
Turns out, expression B is faster by about a tenth of a second. On my computer the average time is as follows:
Try it for yourself.
Random string generation thanks to this Stack Overflow question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With