I was playing around with some python and came up with this code:
import time
N = 10000000
t1 = time.time()
for _ in range(N):
if 'lol' in ['lol']:
pass
print(time.time() - t1)
t1 = time.time()
for _ in range(N):
if 'lol' == 'lol':
pass
print(time.time() - t1)
so, if I use python2:
(test) C:\Users\test>python test.py
0.530999898911
0.5
(test) C:\Users\test>python test.py
0.531000137329
0.5
(test) C:\Users\test>python test.py
0.528000116348
0.501000165939
And it is nice - I like that second variant is quicker and I should use 'lol' == 'lol' as it is more pythonic way to compare two strings.
But what happens if I use python3:
(test) C:\Users\test>python3 test.py
0.37500524520874023
0.3880295753479004
(test) C:\Users\test>python3 test.py
0.3690001964569092
0.3780345916748047
(test) C:\User\test>python3 test.py
0.37799692153930664
0.38797974586486816
using timeit:
(test) C:\Users\test>python3 -m timeit "'lol' in ['lol']"
100000000 loops, best of 3: 0.0183 usec per loop
(test) C:\Users\test>python3 -m timeit "'lol' == 'lol'"
100000000 loops, best of 3: 0.019 usec per loop
O my god! Why first variant is quicker? So should I use ugly style like 'lol' in ['lol'] when i use python3?
timeitmodulepython3 -m timeit "'lol' == 'lol'"'lol' in ['lol']when i use python3?" - No, no, no, no, no, no. As others have already said, you primary goal should be making readable code. Only optimize when you have to. Remember, code is written once but read many times. Also, I have doubts if usinginis truly faster.