在我的优化任务中,我发现内置的split()方法比re.split()方法快大约40%。
一个虚拟基准测试(很容易复制粘贴):
import re, time, random
def random_string(_len):
letters = "ABC"
return "".join([letters[random.randint(0,len(letters)-1)] for i in range(_len) ])
r = random_string(2000000)
pattern = re.compile(r"A")
start = time.time()
pattern.split(r)
print "with re.split : ", time.time() - start
start = time.time()
r.split("A")
print "with built-in split : ", time.time() - start为什么会有这样的差异?
发布于 2011-09-21 22:36:03
预期会更慢,因为使用正则表达式会产生一些开销。
当然,如果对常量字符串进行拆分,则没有必要使用re.split()。
发布于 2011-09-22 01:13:21
有疑问的时候,check the source code。您可以看到,Python s.split()针对空格和内联进行了优化。但s.split()仅适用于固定分隔符。
对于速度的权衡,基于re.split正则表达式的拆分要灵活得多。
>>> re.split(':+',"One:two::t h r e e:::fourth field")
['One', 'two', 't h r e e', 'fourth field']
>>> "One:two::t h r e e:::fourth field".split(':')
['One', 'two', '', 't h r e e', '', '', 'fourth field']
# would require an addition step to find the empty fields...
>>> re.split('[:\d]+',"One:two:2:t h r e e:3::fourth field")
['One', 'two', 't h r e e', 'fourth field']
# try that without a regex split in an understandable way...re.split()只慢了29% (或者s.split()只快了40% ),这应该是令人惊叹的。
发布于 2011-09-21 22:35:39
运行正则表达式意味着您正在为每个字符运行状态机。对一个常量字符串进行拆分意味着您只是在搜索该字符串。第二个过程要简单得多。
https://stackoverflow.com/questions/7501609
复制相似问题