我试图使用timeit
模块比较re.match
和{
>>> s1 = '''
... import re
... re.search(r'hello','helloab'*100000)
... '''
>>> timeit.timeit(stmt=s1,number=10000)
32.12064480781555
>>> s = '''
... import re
... re.match(r'hello','helloab'*100000)
... '''
>>> timeit.timeit(stmt=s,number=10000)
30.9136700630188
现在,我知道match会在字符串的开头查找模式,如果找到就返回一个对象,但是我想知道的是搜索是如何操作的。在
搜索是否会在开始时找到字符串后执行任何额外的匹配,从而减慢搜索速度?在
更新
在使用了@David Robinsons代码后,我得到了与他相似的结果。在
^{pr2}$所以,更新后的问题是为什么search
表现不佳match
?在
在这个使用文本字符串而不是regex模式的特定实例中,对于默认CPython实现,
re.search
确实比re.match
稍快一些(我没有在Python的其他实例中测试过这一点)。在查看C code behind those modules,搜索代码似乎有一个内置的优化to quickly match patterns prefixed with a string lateral。在上面的例子中,整个模式是一个没有正则表达式模式的文本字符串,因此这个经过优化的路由用于匹配整个模式。在
请注意,一旦我们引入正则表达式符号,并且随着字符串前缀变短,性能将如何降低:
^{pr2}$对于包含regex模式的部分模式,SRE_MATCH用于确定匹配项。这与
re.match
后面的代码基本相同。在注意,如果模式以regex模式而不是文本字符串开始,那么结果是如何接近的(与
re.match
稍微快一点)。在换句话说,忽略}快。在
search
和match
有不同的目的,只有当模式是文本字符串时,re.search
比{当然,如果使用的是文本字符串,那么使用字符串操作可能会更好。在
在我的机器(Mac OS 10.7.3上的Python 2.7.3,1.7 GHz Intel Core i5)上,当完成字符串构造、导入re和regex编译并执行10000000次迭代(而不是10次)后,我发现相反的情况:
相关问题 更多 >
编程相关推荐