re.match vs re.search performance difference

后端 未结 2 1792
北荒
北荒 2021-02-19 01:53

I tried to compare re.match and re.search using timeit module and I found that match was better than search when the string I want to foun

2条回答
  •  孤城傲影
    2021-02-19 02:35

    On my machine (Python 2.7.3 on Mac OS 10.7.3, 1.7 GHz Intel Core i5), when done putting the string construction, importing re, and the regex compiling in setup, and performing 10000000 iterations instead of 10, I find the opposite:

    import timeit
    
    print timeit.timeit(stmt="r.match(s)",
                 setup="import re; s = 'helloab'*100000; r = re.compile('hello')",
                 number = 10000000)
    # 6.43165612221
    print timeit.timeit(stmt="r.search(s)",
                 setup="import re; s = 'helloab'*100000; r = re.compile('hello')",
                number = 10000000)
    # 3.85176897049
    

提交回复
热议问题