When determining whether an instance of substring exists in a larger string,
I am considering two options:
(1)
if "aaaa" in "bbbaaaaaabbb":
dosomething()
(2)
pattern = re.compile("aaaa")
if pattern.search("bbbaaaaaabbb"):
dosomething()
Which of the two are more efficient & faster (considering the size of the string is huge)??
Is there any other option that is faster??
Thanks
Regex will be slower.
$ python -m timeit '"aaaa" in "bbbaaaaaabbb"'
10000000 loops, best of 3: 0.0767 usec per loop
$ python -m timeit -s 'import re; pattern = re.compile("aaaa")' 'pattern.search("bbbaaaaaabbb")'
1000000 loops, best of 3: 0.356 usec per loop
Option (1) definitely is faster. For the future, do something like this to test it:
>>> import time, re
>>> if True:
... s = time.time()
... "aaaa" in "bbbaaaaaabbb"
... print time.time()-s
...
True
1.78813934326e-05
>>> if True:
... s = time.time()
... pattern = re.compile("aaaa")
... pattern.search("bbbaaaaaabbb")
... print time.time()-s
...
<_sre.SRE_Match object at 0xb74a91e0>
0.0143280029297
gnibbler's way of doing this is better, I never really played around with interpreter options so I didn't know about that one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With