Updated: now I got pfaut's code to go.
Neat! And faster (just) than the goto.
However, with some adaption, pfaut's insight at Re: Eek! goto? allow's me to double the speed for this bit and save cycles earlier by avoiding spliting or unpacking the string to emulate the char[].
Rate demerphq gotoit pfaut
demerphq 916/s -- -1% -49%
gotoit 923/s 1% -- -49%
pfaut 1809/s 98% 96% --
Benchmark and full results
c:\test>
#! perl -slw
use strict;
use Benchmark qw[cmpthese];
sub demerphq {
my ($len, @k) = @_;
my ($a, $b, $c) = (0)x3;
{
($len or last) and $a+= $k[0];
($len >= 2 or last) and $a+= $k[1] <<8;
($len >= 3 or last) and $a+= $k[2] <<16;
($len >= 4 or last) and $a+= $k[3] <<24;
($len >= 5 or last) and $b+= $k[4];
($len >= 6 or last) and $b+= $k[5] <<8;
($len >= 7 or last) and $b+= $k[6] <<16;
($len >= 8 or last) and $b+= $k[7] <<24;
($len >= 9 or last) and $c+= $k[8] <<8;
($len >= 10 or last) and $c+= $k[9] <<16;
($len >= 11 or last) and $c+= $k[10] <<24;
}
return ($a+$b+$c);
}
sub gotoit {
my ($len, @k) = @_;
my ($a, $b, $c) = (0)x3;
goto "LAST".$len;
LAST11: $c+= $k[10] <<24;
LAST10: $c+= $k[9] <<16;
LAST9: $c+= $k[8] <<8;
LAST8: $b+= $k[7] <<24;
LAST7: $b+= $k[6] <<16;
LAST6: $b+= $k[5] <<8;
LAST5: $b+= $k[4];
LAST4: $a+= $k[3] <<24;
LAST3: $a+= $k[2] <<16;
LAST2: $a+= $k[1] <<8;
LAST1: $a+= $k[0];
LAST0: return ($a+$b+$c);
}
sub pfaut {
my ($k) = @_;
my ($a, $b, $c) = unpack 'L3', $k.(chr(0)x11) ;
return ($a||0) + ($b||0) + ($c||0)<<8;
}
print 'demerphq', demerphq( $_, (65) x $_) for 0 .. 11;
print 'gotoit' , gotoit( $_, (65) x $_) for 0 .. 11;
print 'pfaut' , pfaut( 'A' x $_) for 0 .. 11;
cmpthese( -10, {
demerphq => q[demerphq( $_, (65) x $_) for 0 .. 11;],
gotoit => q[ gotoit( $_, (65) x $_) for 0 .. 11;],
pfaut => q[ pfaut( 'A' x $_) for 0 .. 11;],
});
__END__
c:\test>234554.pl
demerphq0
demerphq65
demerphq16705
demerphq4276545
demerphq1094795585
demerphq1094795650
demerphq1094812290
demerphq1099072130
demerphq2189591170
demerphq2189607810
demerphq2193867650
demerphq3284386690
gotoit0
gotoit65
gotoit16705
gotoit4276545
gotoit1094795585
gotoit1094795650
gotoit1094812290
gotoit1099072130
gotoit2189591170
gotoit2189607810
gotoit2193867650
gotoit3284386690
pfaut0
pfaut16640
pfaut4276480
pfaut1094795520
pfaut1094795520
pfaut1094812160
pfaut1099072000
pfaut2189591040
pfaut2189591040
pfaut2189607680
pfaut2193867520
pfaut3284386560
Benchmark:
running
demerphq, gotoit, pfaut
, each for at least 10 CPU seconds
...
demerphq: 11 wallclock secs (10.56 usr + 0.00 sys = 10.56 CPU) @ 91
+5.87/s (n=9667)
gotoit: 11 wallclock secs (10.80 usr + 0.00 sys = 10.80 CPU) @ 92
+2.72/s (n=9970)
pfaut: 10 wallclock secs (10.14 usr + 0.00 sys = 10.14 CPU) @ 18
+09.27/s (n=18337)
Rate demerphq gotoit pfaut
demerphq 916/s -- -1% -49%
gotoit 923/s 1% -- -49%
pfaut 1809/s 98% 96% --
c:\test>
</code>
Examine what is said, not who speaks.
The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.