I have next 2 blocks of code:
def replace_re(text):
start = time.time()
new_text = re.compile(r'(\n|\s{4})').sub('', text)
finish = time.time()
return finish - start
def replace_builtin(text):
start = time.time()
new_text = text.replace('\n', '').replace(' ', '')
finish = time.time()
return finish - start
Than I call both functions with text param (~500kb of source code of one web-page).
I thought replace_re() will be much faster, but results are the next:
replace_builtin() ~ 0.008 secreplace_re() ~ 0.035 sec (nearly 4.5 times slower!!!)Why is that?
Because regular expressions are more than 4.5 times more complex than a fixed string replacement.
Because an re has to generate a FSM. Then use that to process the string. While a replace can use the underlying string processing functions closer to the lib/OS levels.
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