Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Rotating a string

by nashdj (Friar)
on Dec 04, 2000 at 12:29 UTC ( [id://44765]=note: print w/replies, xml ) Need Help??


in reply to Rotating a string

Is substr faster than a regex like:

sub rot { my $str = shift; my $rot = (shift) % length($str); # to rotate more than once $str =~ s/(.{$rot})(.*)/$2$1/; $str; }

?

Replies are listed 'Best First'.
Re: Re: Rotating a string
by chipmunk (Parson) on Dec 04, 2000 at 20:30 UTC
    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://44765]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2024-04-19 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found