O Wise Ones,

In my quest to compare equivalent regular expressions, I have attempted to reduce duplicate code by moving the "testing" to a subroutine. The odd thing is that when moved into a subroutine, alternation takes about the same time as when using character classes.

-------------
Without the sub:
(Output =
Alternation takes 1.395 seconds.
Character class 0.043 seconds.
)
-------------
use strict; use Time::HiRes 'time'; sub main { my $TimesToDo = 1000; my $TestString ="abababdedfg" x 1000; my $Count = $TimesToDo; my $StartTime = time(); while ($Count-- > 0) { $TestString =~m/^(a|b|c|d|e|f|g)+$/; } my $EndTime = time(); printf("Alternation takes %.3f seconds.\n", $EndTime - $StartTime) +; $Count = $TimesToDo; $StartTime = time(); while ($Count-- > 0) { $TestString =~m/^[a-g]+$/; } $EndTime = time(); printf("Character class %.3f seconds.\n", $EndTime - $StartTime); } unless (caller) {main ()}

----------
With the sub:
(Output =
Alternation takes 0.000 seconds.
Character class 0.001 seconds.
)
----------
use strict; use Time::HiRes 'time'; #TimesToDo, TestString, Regex sub test { my $TimesToDo = shift; my $TestString = shift() x 1000; my $Count = $TimesToDo; my $StartTime = time(); while ($Count-- > 0) { $TestString =~m/^$_[2]+$/; } my $EndTime = time(); return $EndTime - $StartTime; } sub main { my $result = test(1000,"abababdedfg","(a|b|c|d|e|f|g)"); printf("Alternation takes %.3f seconds.\n", $result); $result = test(1000,"abababdedfg","[a-g]"); printf("Character class %.3f seconds.\n", $result); } unless (caller) {main ()}

Very greatful for any responses!

In reply to Benchmarking regexes by Anonymous Monk

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.