我曾以为startswith
必须比in
更快,因为in
需要进行更多的检查(允许搜索的单词可以在字符串中的任何位置)。但我有些怀疑,所以我决定使用timeit
来测试一下。如下是计时代码,您可能会注意到我并没有做太多计时;这段代码非常简单。
import timeit
setup1='''
def in_test(sent, word):
if word in sent:
return True
else:
return False
'''
setup2='''
def startswith_test(sent, word):
if sent.startswith(word):
return True
else:
return False
'''
print(timeit.timeit('in_test("this is a standard sentence", "this")', setup=setup1))
print(timeit.timeit('startswith_test("this is a standard sentence", "this")', setup=setup2))
结果:
>> in: 0.11912814951705597
>> startswith: 0.22812353561129417
所以startswith
要慢两倍!...鉴于我之前的说法,我觉得这种行为非常令人困惑。我在计时这两个函数时是否做错了什么,或者in
确实更快?如果是这样,为什么呢?请注意,即使它们都返回
False
,结果也非常相似(在这种情况下,in
必须在简单的短路之前实际遍历整个句子):print(timeit.timeit('in_test("another standard sentence, would be that", "this")', setup=setup1))
print(timeit.timeit('startswith_test("another standard sentence, would be that", "this")', setup=setup2))
>> in: 0.12854891578786237
>> startswith: 0.2233201940338861
如果我需要从头开始实现这两个函数,它们大致如下(伪代码):
startswith:一次一个地将word的字母与sentence的字母进行比较,直到a)用尽word(返回True)或b)检查返回False(返回False)
in
:对于可以在sentence中找到word的初始字母的每个位置调用startswith
。我就是不明白...
请注意,
in
和startswith
是不等价的;我只是谈论需要在字符串中找到的单词必须是第一个的情况。