When to compile regex?

Tim Ottinger tottinge at concentric.net
Mon Feb 28 08:50:31 EST 2000


On Sun, 13 Feb 2000 07:02:42 -0500, David Shochat
<shochat at chelmsford.com> wrote:

>In section 4.2.3 of the Python Library Reference (1.5.2) it says that
>using compile is more efficient "when the expresion will be used several
>times in a single program". I'm trying to figure out the intended
>meaning of this. Does that mean "executed more than once", or "occurs
>more than once in the program text"? Specifically, if it only occurs
>once, but that is in a loop, is there an advantage to compiling before
>entering the loop?

It has to be compiled before it's used. If you don't compile it, then
it will be compiled at the point of use, as a temporary, and then
tossed away later. 

If you use the expression exactly once, or very rarely, or speed just
doesn't matter at all, then don't compile.

If you are going to use the expression a lot, in many searches, and
especially in loops, then compiling can save you some time. It won't
be a run/no-run issue, just a timing issue.

Personally, I like to see the expression compile exception at compile
time. Just me, though. YMMV.

Tim (No-not-THAT-tim-ly yours)



More information about the Python-list mailing list