, .
: .
, , . , .
, , , .
$ speed.py
inarray x 1000000: 0.277590343844
comparison x 1000000: 0.347808290754
makearray x 1000000: 0.408771123295
import timeit
NUM = 1000000
a = 1
b = 2
c = 3
d = 1
array = {b,c,d}
tup = (b,c,d)
lst = [b,c,d]
def comparison():
if a == b or a == c or a == d:
pass
def makearray():
if a in {b, c, d}:
pass
def inarray():
if a in array:
pass
def maketuple():
if a in (b,c,d):
pass
def intuple():
if a in tup:
pass
def makelist():
if a in [b,c,d]:
pass
def inlist():
if a in lst:
pass
def time_all(funcs, params=None):
timers = []
for func in funcs:
if params:
tx = timeit.Timer(lambda: func(*params))
else:
tx = timeit.Timer(lambda: func())
timers.append([func, tx.timeit(NUM)])
for func, speed in sorted(timers, key=lambda x: x[1]):
print "{fn:<25} x {n}: ".format(fn=func.func_name, n=NUM), speed
print ""
return
time_all([comparison,
makearray,
inarray,
intuple,
maketuple,
inlist,
makelist
],
)
This will not quite answer your question regarding the reason why you do not often see comparisons using. I would speculate, but this is probably a mixture of 1,2,4, and a situation where the author needed to write this specific code.
I personally used both methods depending on the situation. The choice usually came down to speed or simplicity.
edit:
@ bracco23 is right, there are slight differences where the use of tuples vs array vs list will change the time.
$ speed.py
inarray x 1000000: 0.260784980761
intuple x 1000000: 0.288696420718
inlist x 1000000: 0.311479982167
maketuple x 1000000: 0.356532747578
comparison x 1000000: 0.360010093964
makearray x 1000000: 0.41094386108
makelist x 1000000: 0.433603059099