in reply to Re: Rotating a string
in thread Rotating a string

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.

Replies are listed 'Best First'.
Re: Re: Re: Rotating a string
by merlyn (Sage) on Dec 04, 2000 at 20:40 UTC