Here is the reason why my approach was a 'touch' slower than Grantm's, but both are much faster than others:

Say both of us are trying to match the 3rd word, his regexp only matches the 3rd word, but for the first word and the second word, there is no matching done (to be more precise, no extra effort to make sure backref can happen); But in my case, I am matching all 3 words up to the 3rd one. Although I end up with having the third word stored in $1 just as his does, extra effort are taken to handle the 1st and 2nd words, to make sure the backref for the immediate next one works.

But in both cases (mine and Grantm's), the effort is only up to the 3rd word, not like in some other cases, the matching continues to the end of the string.

Performance (timing) is just one benefit gained here, the other benefit is we used less space, as we don't create an array to hold all words.

Now let's play a little bit math. Remember you mentioned the O and O/2 observation?

Assume we have a string formed up with m words, and the effort to matching one word is n, in the testing you designed:

So they are close to O : O/2.

In reply to Re: "Capturing the nth word in a string" Algorithm Analysis by pg
in thread "Capturing the nth word in a string" Algorithm Analysis by Roger

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.