Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8568209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T18:03:38+00:00 2026-06-11T18:03:38+00:00

From the Python docs for re.compile() : Note The compiled versions of the most

  • 0

From the Python docs for re.compile():

Note The compiled versions of the most recent patterns passed to
re.match(), re.search() or re.compile() are cached, so programs that
use only a few regular expressions at a time needn’t worry about
compiling regular expressions.

However, in my testing, this assertion doesn’t seem to hold up. When timing the following snippets that use the same pattern repeatedly, the compiled version is still substantially faster than the uncompiled one (which should supposedly be cached).

Is there something I am missing here that explains the time difference?

import timeit

setup = """
import re
pattern = "p.a.t.t.e.r.n"
target = "p1a2t3t4e5r6n"
r = re.compile(pattern)
"""

print "compiled:", \
    min(timeit.Timer("r.search(target)", setup).repeat(3, 5000000))
print "uncompiled:", \
    min(timeit.Timer("re.search(pattern, target)", setup).repeat(3, 5000000))

Results:

compiled: 2.26673030059
uncompiled: 6.15612802627
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T18:03:39+00:00Added an answer on June 11, 2026 at 6:03 pm

    Here’s the (CPython) implementation of re.search:

    def search(pattern, string, flags=0):
        """Scan through string looking for a match to the pattern, returning
        a match object, or None if no match was found."""
        return _compile(pattern, flags).search(string)
    

    and here is re.compile:

    def compile(pattern, flags=0):
        "Compile a regular expression pattern, returning a pattern object."
        return _compile(pattern, flags)
    

    which relies on re._compile:

    def _compile(*key):
        # internal: compile pattern
        cachekey = (type(key[0]),) + key
        p = _cache.get(cachekey)            #_cache is a dict.   
        if p is not None:
            return p
        pattern, flags = key
        if isinstance(pattern, _pattern_type):
            if flags:
                raise ValueError('Cannot process flags argument with a compiled pattern')
            return pattern 
        if not sre_compile.isstring(pattern):
            raise TypeError, "first argument must be string or compiled pattern"
        try:
            p = sre_compile.compile(pattern, flags)
        except error, v:
            raise error, v # invalid expression
        if len(_cache) >= _MAXCACHE:
            _cache.clear()
        _cache[cachekey] = p
        return p
    

    So you can see that as long as the regex is already in the dictionary, the only extra work involved is the lookup in the dictionary (which involves creating a few temporary tuples, a few extra function calls …).

    Update
    In the good ole’ days (the code copied above), the cache used to be completely invalidated when it got too big. These days, the cache cycles — dropping the oldest items first. This implementation relies on the ordering of python dictionaries (which was an implementation detail until python3.7). In Cpython before python3.6, this would have dropped an arbitrary value out of the cache (which is arguably still better than invalidating the whole cache)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

From Python docs: http://docs.python.org/library/stdtypes.html#comparisons Implementation note: Objects of different types except numbers are ordered
Quoting from docs.python.org : sys.argv The list of command line arguments passed to a
I try to use doctest from example from http://docs.python.org/library/doctest.html But when I run python
What is the python keyword with used for? Example from: http://docs.python.org/tutorial/inputoutput.html >>> with open('/tmp/workfile',
From the python docs: The various exec*() functions take a list of arguments for
I tried to run the following code from http://docs.python.org/library/mmap.html import mmap # write a
Using an example from the Python DOCs: stocks = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
This is a simple example from the python documentation (http://docs.python.org/extending/extending.html): static PyObject * spam_system(PyObject
Python documentation from http://docs.python.org/library/string.html : string.lstrip(s[, chars]) Return a copy of the string with
I have picked a snippet from http://docs.python.org/library/multiprocessing.html#multiprocessing-examples import multiprocessing def queue_func(queue): for i in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.