Reg-Ex and lambda optimization

Sean 'Shaleh' Perry shalehperry at attbi.com
Sun Dec 30 00:08:43 EST 2001


> 
>     Is the re.match('^db.*$',s) compiled each iteration of the loop lookup?
> 
> I don't notice this being slow, but was curious if this was bad coding.
> 

from sre.py in 2.2:

def match(pattern, string, flags=0):
    """Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found."""
    return _compile(pattern, flags).match(string)

def _compile(*key):
    # internal: compile pattern
    p = _cache.get(key)
    if p is not None:
        return p
    pattern, flags = key
    if type(pattern) not in sre_compile.STRING_TYPES:
        return pattern
    try:
        p = sre_compile.compile(pattern, flags)
    except error, v:
        raise error, v # invalid expression
    if len(_cache) >= _MAXCACHE:
        _cache.clear()
    _cache[key] = p
    return p

So the first time you get all of the way through _compile, after that the cache
hits and you hit the first return on line 3.  One extra dictionary lookup
and one function call each re.match call may or may not matter in the grand
scheme of things.




More information about the Python-list mailing list