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

时间:2017-02-14 13:48:48

标签: python regex

想象一下像这样的字符串列表:('{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] == '{':

哪一个最快?是否有一些比这四个选项更快?

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

正如@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