python处理字符串效率_Python字符串搜索效率
可能是當(dāng)然是第二個,我認(rèn)為在大字符串中搜索和在小字符串中搜索沒有任何區(qū)別。由于行較短,您可能會跳過一些字符,但拆分操作也有其成本(搜索\n,創(chuàng)建n個不同的字符串,創(chuàng)建列表),循環(huán)是在python中完成的。
string__contain__方法是用C實(shí)現(xiàn)的,因此速度明顯更快。
還可以考慮,一旦找到第一個匹配項(xiàng),第二個方法就會終止,但第一個方法在開始搜索字符串內(nèi)部之前會將所有字符串分割開來。
這一點(diǎn)通過一個簡單的基準(zhǔn)得到了迅速的證明:import timeit
prepare = """
with open('bible.txt') as fh:
text = fh.read()
"""
presplit_prepare = """
with open('bible.txt') as fh:
text = fh.read()
lines = text.split('\\n')
"""
longsearch = """
'hello' in text
"""
splitsearch = """
for line in text.split('\\n'):
if 'hello' in line:
break
"""
presplitsearch = """
for line in lines:
if 'hello' in line:
break
"""
benchmark = timeit.Timer(longsearch, prepare)
print "IN on big string takes:", benchmark.timeit(1000), "seconds"
benchmark = timeit.Timer(splitsearch, prepare)
print "IN on splitted string takes:", benchmark.timeit(1000), "seconds"
benchmark = timeit.Timer(presplitsearch, presplit_prepare)
print "IN on pre-splitted string takes:", benchmark.timeit(1000), "seconds"
結(jié)果是:IN on big string takes: 4.27126097679 seconds
IN on splitted string takes: 35.9622690678 seconds
IN on pre-splitted string takes: 11.815297842 seconds
總結(jié)
以上是生活随笔為你收集整理的python处理字符串效率_Python字符串搜索效率的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python日志_python日志处理
- 下一篇: 浏览器接收响应数据过大_DOM总结:数据