Even faster than index() or a regex -- I would imagine -- would be substr() and eq together.

When imagine when you can Benchmark?

use Benchmark 'cmpthese'; my $str1 = 'foobarbazqux'; my $str2 = 'foobar'; my $str2len = length $str2; cmpthese (3e6, { regex => sub { $str1 =~ /\Q$str2/; }, regex2 => sub { $str1 =~ /\Q$str2/o; }, ## probably useless test, +see japhy's comment below index => sub { index $str1, $str2; }, substr => sub { $str2 eq substr $str1, 0, length $str2; }, substr2 => sub { $str2 eq substr $str1, 0, $str2len; }, }); __END__ Rate regex regex2 substr substr2 index regex 1063830/s -- -13% -25% -43% -72% regex2 1229508/s 16% -- -14% -34% -68% substr 1421801/s 34% 16% -- -23% -63% substr2 1851852/s 74% 51% 30% -- -51% index 3797468/s 257% 209% 167% 105% --

The index solution is clearly superior to the others. It's interesting to see the improvements of regex2 and substr2 over their unoptimized counterparts.

Update: I forgot that the OP was matching at the beginning of the string. This is a better benchmark:

use Benchmark 'cmpthese'; my $str1 = 'foobarbazqux'; my $str2 = 'foobar'; my $str2len = length $str2; cmpthese (3e6, { regex => sub { $str1 =~ /^\Q$str2/; }, index => sub { 0 == index $str1, $str2; }, substr => sub { $str2 eq substr $str1, 0, length $str2; }, substr2 => sub { $str2 eq substr $str1, 0, $str2len; }, }); __END__ Rate regex substr substr2 index regex 671141/s -- -59% -65% -71% substr 1630435/s 143% -- -16% -30% substr2 1935484/s 188% 19% -- -17% index 2343750/s 249% 44% 21% --

--
David Serrano


In reply to Re^2: Regex Start Anchor with variables by Hue-Bond
in thread Regex Start Anchor with variables by chrism01

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.