Precompiled regular expressions slower?

Peter Bienstman pbienst at mit.edu
Tue Feb 26 11:17:53 EST 2002


Hi,

I've a Python script a want to optimise. It basically loops over all the 
lines in a file and does some regular expression matching:

line = inputfile.readline()
while line:
  s = search(r".....", line)
  ...
  line = inputfile.readline()

There are several reg ex in the loop. Since the Python version runs 2 to 3 
times as slow as its Perl counterpart, I thought I'd try speeding up the 
script by precompiling the reg ex:

re1 = compile(r"....") 
...
line = inputfile.readline()
while line:
  s = search(re1, line)
  ...
  line = inputfile.readline()


Strangely enough this new version seems to run about 30% *slower* than the 
old version.

Am I missing something here? (I'm using Python 2.1)

Peter



More information about the Python-list mailing list