python处理字符串效率_Python字符串搜索效率

可能是当然是第二个,我认为在大字符串中搜索和在小字符串中搜索没有任何区别。由于行较短,您可能会跳过一些字符,但拆分操作也有其成本(搜索\n,创建n个不同的字符串,创建列表),循环是在python中完成的。

string__contain__方法是用C实现的,因此速度明显更快。

还可以考虑,一旦找到第一个匹配项,第二个方法就会终止,但第一个方法在开始搜索字符串内部之前会将所有字符串分割开来。

这一点通过一个简单的基准得到了迅速的证明: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"

结果是: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值