Let's find out... (I like your idea of using modulus on the rotate parameter first, but I left that out of the benchmark so that the comparison would be fair.)
#!/usr/local/bin/perl -w use Benchmark; @long = ('a' x 100, 45); @short = ('a' x 10, 7); timethese( -10, { L_ariels => sub { ariels(@long) }, L_merlyn => sub { merlyn(@long) }, L_nashdj => sub { nashdj(@long) }, S_ariels => sub { ariels(@short) }, S_merlyn => sub { merlyn(@short) }, S_nashdj => sub { nashdj(@short) }, } ); sub ariels { my ($str, $rot) = @_; scalar reverse ((reverse substr($str,0,$rot)) . (reverse substr($str,$rot)) ); } sub merlyn { my ($str, $rot) = @_; substr($str,$rot) . substr($str, 0, $rot); } sub nashdj { my ($str, $rot) = @_; $str =~ s/(.{$rot})(.*)/$2$1/s; $str; }
And the results:

Benchmark: running L_ariels, L_merlyn, L_nashdj, S_ariels, S_merlyn, S_nashdj,
each for at least 10 CPU seconds...
  L_ariels: 13 wallclock secs ( 9.97 usr +  0.04 sys = 10.01 CPU) @ 71186.51/s (n=712577)
  L_merlyn: 10 wallclock secs ( 9.95 usr +  0.06 sys = 10.01 CPU) @ 92000.70/s (n=920927)
  L_nashdj: 12 wallclock secs ( 9.95 usr +  0.06 sys = 10.01 CPU) @ 25479.52/s (n=255050)
  S_ariels: 11 wallclock secs ( 9.99 usr +  0.07 sys = 10.06 CPU) @ 89239.76/s (n=897752)
  S_merlyn: 13 wallclock secs ( 9.95 usr +  0.05 sys = 10.00 CPU) @ 100328.30/s (n=1003283)
  S_nashdj: 10 wallclock secs (10.27 usr +  0.10 sys = 10.37 CPU) @ 28213.11/s (n=292570)
So, using substr is in fact quite a bit faster than using a regex. I think this is not surprising: the substitution being done is too simple to make the overhead of the regex engine worthwhile.


In reply to Re: Re: Rotating a string by chipmunk
in thread Rotating a string by ariels

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.