[英]Why is any() so much faster than in?
https://repl.it/@ArmanTavakoli/List-Comprehension-vs-Any https://repl.it/@ArmanTavakoli/List-Comprehension-vs-Any
Why is my any
check so much faster than my in
check when they are essentially doing the same thing? 为什么我的
any
检查,因此速度远远超过我in
办理入住手续时,他们基本上做同样的事情?
from timeit import default_timer as timer
import random
input = [random.randint(0, 100) for x in range(0, 1000000)]
def any_check(input):
return any(i == 1 for i in input)
def list_comprehension(input):
return 1 in [num for num in input]
first_start = timer()
any_check(input)
first_end = timer()
print('any_check', first_end - first_start)
second_start = timer()
list_comprehension(input)
second_end = timer()
print('list_comprehension', second_end - second_start)
Results of running the functions 3 times each. 每个函数运行3次的结果。
# Calculated with 3 runs each
# Ratio is list_comprehension:any_check
# 10,000 - Mean Ratio: 17.87
# Example run;
# any_check 1.5022000297904015e-05
# list_comprehension 0.00038980199315119535
# 100,000 - Mean Ratio: 140.76
# any_check 2.020499960053712e-05
# list_comprehension 0.0035961729954578914
# 1,000,000 - Mean Ratio: 3379.81
# any_check 2.2904998331796378e-05
# list_comprehension 0.08528400499926647
As several people pointed out in comments, the reason your function doing an in
test is slower than the version using any
is because that function also includes an unnecessary list comprehension that needs to iterate over the whole input before the in
operator can begin looking for a match. 正如一些人在评论中指出的那样,您的函数
in
测试中比使用any
函数的版本慢的原因是,该函数还包括不必要的列表理解,需要对整个输入进行迭代,然后in
运算符才能开始查找比赛。 When run on lists, both in
and any
can short circuit, quitting early if a matching value is found early in the search. 在列表上运行时,
in
或any
都可能短路,如果在搜索的早期找到匹配的值,则尽早退出。 But the list comprehension in your second function always iterates over the whole input even if there was a 1
right at the start. 但是,即使开始时有一个
1
,在第二个函数中的列表理解总是会遍历整个输入。
If you replaced 1 in [num for num in input]
with 1 in input
, you'd see performance as good or better than in your function using any
. 如果用
1 in [num for num in input]
代替1 in [num for num in input]
中的1 in input
与使用any
相比,您会发现性能好于或好于函数。 Performance would be fairly similar if input
was a list, but might be much faster for other container types (such as set
s and range
s). 如果
input
是列表,性能将非常相似,但对于其他容器类型(例如set
和range
)可能会更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.