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?
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.
According to the analysis of bytecode:
>>> dis.dis(compile('a==2==b', '', 'eval'))
1 0 LOAD_NAME 0 (a)
3 LOAD_CONST 0 (2)
6 DUP_TOP
7 ROT_THREE
8 COMPARE_OP 2 (==)
11 JUMP_IF_FALSE_OR_POP 21
14 LOAD_NAME 1 (b)
17 COMPARE_OP 2 (==)
20 RETURN_VALUE
>> 21 ROT_TWO
22 POP_TOP
23 RETURN_VALUE
>>> dis.dis(compile('a==2 and b==2', '', 'eval'))
1 0 LOAD_NAME 0 (a)
3 LOAD_CONST 0 (2)
6 COMPARE_OP 2 (==)
9 JUMP_IF_FALSE_OR_POP 21
12 LOAD_NAME 1 (b)
15 LOAD_CONST 0 (2)
18 COMPARE_OP 2 (==)
>> 21 RETURN_VALUE
Python need more operations to process a==2==b
than a == 2 and b == 2