[Tutor] pattern matching is too slow

Alan G alan.gauld at freenet.co.uk
Fri Aug 12 10:54:51 CEST 2005

while True:
    temp = self.mplayerOut.readline()
       print temp
       if re.compile("^A:").search(temp):

The point of re.compile is to compile the re once *outside* the loop.
Compiling the re is slow so you should only do it outside.

As a first step replace re.compile with re.search

       if re.search("^A:",temp):
          print "abc"
 except StandardError:

As a second step move the compile before the loop

reg = re.compile("^A:")

Then inside the loop use the compiled expression

       if reg.search(temp):

The first step should be faster, the second step faster still.

Finally, lookaing at tyour regex you might be better using 
a simple string method - startswith()

       if temp.startswith("A"):

That should be even faster still.


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list