Regex seems to be faster.
use Inline C;
use Benchmark qw( cmpthese ) ;
my $digits = '1234567891';
my $bob = {
u1 => sub {
return uniq($digits);
},
u2 => sub {
my @l = ();
for my $x (split '', $digits) {
if ($l[$x]++) {
return 1;
}
}
return 0;
},
u3 => sub {
my @l = ();
my $max = length($digits);
for (my $i=0; $i < $max; $i++) {
$x = substr($digits,$i,1);
if ($l[$x]++) {
return 1;
}
}
return 0;
},
u4 => sub {
return $digits !~ /(.).*\1/ ? 0:1;
},
};
print "u1: ", $bob->{u1}->(), "\n";
print "u2: ", $bob->{u2}->(), "\n";
print "u3: ", $bob->{u3}->(), "\n";
print "u4: ", $bob->{u4}->(), "\n";
cmpthese( -5, $bob);
__END__
Rate u2 u3 u4 u1
u2 19725/s -- -10% -90% -95%
u3 21847/s 11% -- -89% -94%
u4 204817/s 938% 838% -- -44%
u1 367282/s 1762% 1581% 79% --
__C__
int uniq(char* name) {
int bob[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int max = strlen(name);
int x;
for (x = 0; x < max; x++) {
if (bob[name[x]-'0']++) {
return 1;
}
}
return 0;
}
-- gam3
A picture is worth a thousand words, but takes 200K.
|