If you want to know which will be faster, then you need to benchmark. My gut feeling is that alternation will be faster than loops, but I could easily be wrong. There will also be details in exactly what you are searching for that will affect performance. For example, if your are looking for the words "fox", "fred" or "frodo", then the regular expression /f(r((odo)|(ed)))|(ox)/ might be faster than a simpler matcher for each word separately. On the other hand perhaps the perl regular expression engine will do that optimisation for you, so writing the more complex regex above will make difference.

One important tip, is that if the text you are searching for (and therefore the regular expression) is not know at perl compile time, then you can explicitly compile the regular expression at runtime, which will improve performace. Do that with "qr" brackets: my $compiled_re = qr/pattern/

You also asked which is better. That depends on a whole heap of factors, but if readability and maintainability is more important than performance, then forget what I just said, and write a simple algorithm that is easy for anyone to read and understand, even if it is a little slower.


In reply to Re: Alternation vs. looping for multiple searches. by chrestomanci
in thread Alternation vs. looping for multiple searches. by kprice++

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.