Python re.split() 与 split() [英] Python re.split() vs split()
本文介绍了Python re.split() 与 split()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的优化任务中,我发现内置的 split() 方法比等效的 re.split() 方法快 40%.
In my quests of optimization, I discovered that that built-in split() method is about 40% faster that the re.split() equivalent.
一个虚拟基准(易于复制粘贴):
A dummy benchmark (easily copy-pasteable):
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
为什么会有这种差异?
推荐答案
re.split
预计会更慢,因为使用正则表达式会产生一些开销.
re.split
is expected to be slower, as the usage of regular expressions incurs some overhead.
当然,如果您在常量字符串上进行拆分,则使用 re.split()
毫无意义.
Of course if you are splitting on a constant string, there is no point in using re.split()
.
这篇关于Python re.split() 与 split()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文