3 ms·
One perl nicety is that the VM will optimize to only compile the expression once. Python's re.sub() has to compile the expression every time, since it's just a
by CUViper 17y ago
One perl nicety is that the VM will optimize to only compile the expression once. Python's re.sub() has to compile the expression every time, since it's just a string argument rather than a language construct. You can manually cache the result of re.compile() -- it's just not as sugary that way.
- amix 17y agoThat's actually untrue. If you look in the implementation of the `re` module you would see that it caches the compilation of any regular expression.
- CUViper 17y agoAha -- I almost suggested that they could do some memoization, and indeed they are doing just that. The last 100 unique patterns are compiled and stored in a dictionary for future use. You could still thrash badly if your regex "working set" is more than 100 patterns, but for most people it's probably Good Enough. (Plus you could override re._MAXCACHE if you really want.) Thanks for pointing out my error, and getting me to read the actual code instead of speculating. :)