Does Python optimize regexes?

Michael Geary Mike at DeleteThis.Geary.com
Tue Jun 29 09:50:46 EDT 2004


Peter Otten wrote:
> Python puts the compiled regular expressions into a cache. The relevant
> code is in sre.py:
>
> def match(pattern, string, flags=0):
>     return _compile(pattern, flags).match(string)
>
> ...
>
> def _compile(*key):
>     p = _cache.get(key)
>     if p is not None:
>         return p
> ...
>
> So not explicitly calling compile() in advance only costs you two function
> calls and a dictionary lookup - and maybe some clarity in your code.

That cost can be significant. Here's a test case where not precompiling the
regular expression increased the run time by more than 50%:

http://groups.google.com/groups?selm=10b48qllaagcr11%40corp.supernews.com

-Mike





More information about the Python-list mailing list