Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's faster, a==2==b, or a==2 and b==2

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?

like image 287
noɥʇʎԀʎzɐɹƆ Avatar asked Feb 09 '23 20:02

noɥʇʎԀʎzɐɹƆ


1 Answers

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:

  • A: 0.22025904178619385 seconds
  • B: 0.3740460252761841 seconds

Try it for yourself.

Random string generation thanks to this Stack Overflow question.

like image 178
noɥʇʎԀʎzɐɹƆ Avatar answered Feb 15 '23 10:02

noɥʇʎԀʎzɐɹƆ