繁体   English   中英

比较字符串开头的最快方法是什么?

[英]What is the fastest way to compare beginning of a string?

想象一下这样的字符串列表: ('{hello world} is awesome', 'Hello world is less awesome', '{hello world} is {awesome} too') 我想检查每个字符串的起始字符周期,我想我有4个选择:

if re.search(r'^\{', i):
if re.match(r'\{', i):
if i.startswith('{'):
if i[:1] == '{':

哪一个最快? 有没有比这4个选项更快的选项?

注意:要比较的起始字符串可能更长,而不仅仅是一个字母,例如{hello

最快的是i[0] == value ,因为它直接使用指向基础数组的指针。 正则表达式需要(至少)解析模式,而startsWith则需要进行方法调用并在实际比较之前创建该大小的切片。

就像@dsqdfg在评论中说的那样,python中有一个计时功能,到目前为止我还不知道。 我尝试测量它们,结果如下:

python -m timeit -s 'text="{hello world}"' 'text[:6] == "{hello"'
1000000 loops, best of 3: 0.224 usec per loop

python -m timeit -s 'text="{hello world}"' 'text.startswith("{hello")'
1000000 loops, best of 3: 0.291 usec per loop

python -m timeit -s 'text="{hello world}"' 'import re' 're.match(r"\{hello", text)'
100000 loops, best of 3: 2.53 usec per loop

python -m timeit -s 'text="{hello world}"' 'import re' 're.search(r"^\{hello", text)'
100000 loops, best of 3: 2.86 usec per loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM