我很想知道直接比较与检查数组之间的时间差异是什么。
结论:构建数组的成本不是免费的,在考虑速度差异时必须考虑到。
如果在比较时正在构建数组,则从技术上讲它比简单比较慢。因此,简单的比较在循环内或循环外会更快。
也就是说,如果数组已经构建好了,那么在大循环中检查数组会比进行简单的比较更快。
$ 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
],
)
这并不能完全回答您关于您不经常看到使用 in 进行比较的原因的问题。我会推测,但它可能是 1、2、4 的混合,以及作者需要的情况编写特定的代码。
我个人根据情况使用了这两种方法。选择通常归结为速度或简单性。
编辑:
@bracco23 是对的,使用元组 vs 数组 vs 列表会改变时间。
$ 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