Python 字符串替换效率 replace> re.sub

2019-05-08 10:38:54 +08:00
 sunhk25
import re,timeit
str = "abcdefghigkqpwueriwutghlskajdf,mnbz,xcnvoiequynf12341234321065498+7mnbz,xcnvoiequynf12341234321065498+7mnbz,xcnvoiequynf12341234321065498+7mnbz,xcnvoiequynf12341234321065498+7"

# pattern1
start = timeit.default_timer()
for i in range(1000000):
    tst = re.sub("mn|123|[abcdef7]", "", str)
stop = timeit.default_timer()
print('pattern1', 'Time: ', stop - start)

# pattern2
start = timeit.default_timer()
for i in range(1000000):
    tst = str.replace("mn", "")
    tst = tst.replace("123", "")
    tst = tst.replace("a", "")
    tst = tst.replace("b", "")
    tst = tst.replace("c", "")
    tst = tst.replace("d", "")
    tst = tst.replace("e", "")
    tst = tst.replace("f", "")
    tst = tst.replace("7", "")

stop = timeit.default_timer()
print('pattern2', 'Time: ', stop - start)

# pattern3
start = timeit.default_timer()
for i in range(1000000):
    tst = re.sub("mn", "", str)
stop = timeit.default_timer()
print('pattern3', 'Time: ', stop - start)

# pattern4
start = timeit.default_timer()
for i in range(1000000):
    tst = str.replace("mn", "")

stop = timeit.default_timer()
print('pattern4', 'Time: ', stop - start)
# 输出
# pattern1 Time:  10.851562640495892
# pattern2 Time:  4.726493571613192
# pattern3 Time:  1.5144934460814898
# pattern4 Time:  0.5535754144044809
2889 次点击
所在节点    Python
6 条回复
zagfai
2019-05-08 11:02:16 +08:00
原理上就是差很远,sub 的适用性广很多。
Hieast
2019-05-08 11:05:38 +08:00
你用 ipython 自己跑一下下面的代码吧,你的写法有两个很大的问题:
1. 用正则确不先 compile
2. 居然用 str 做变量名

https://gist.github.com/hieast/1fc9e5dad298a62178236c0c7bf9f035.js
sunhk25
2019-05-08 11:47:54 +08:00
@Hieast 我测试的时候也做了用 compile 和不用的区别,感觉没有太大提升,这个例子就没有放里。变量名 abc 啥的我都是随手写的啦,没有计较。
Hieast
2019-05-08 12:59:56 +08:00
@sunhk25 我测的情况是 compile 后 py27 和 py36 都减少了 40% 的运行时间, 正则速度和 replace 差距都不超过一倍,感觉效率方面基本没有讨论的意义了。
一楼的朋友说的很好,正则灵活多了。
whoami9894
2019-05-08 13:04:23 +08:00
@sunhk25
用 abc 做变量名和用 str 做变量名可不是一回事
ipwx
2019-05-08 13:45:24 +08:00
@Hieast re.sub 有编译缓存。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/562095

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX