【发布时间】:2017-11-15 03:42:01
【问题描述】:
我的印象是 startswith 必须比 in 更快,原因很简单,in 必须进行更多检查 (允许查看单词for 位于字符串中的任何位置)。但我有疑问,所以我决定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:在句子中可以找到单词首字母的每个位置调用startswith。
我只是不明白..
澄清一下,in 和 startswith 不等价;我只是在谈论一个人试图找到的单词必须是字符串中的 first 的情况。
【问题讨论】:
标签: python performance python-3.x time