It's the need to check the same digit appearing in different places in
the two strings that makes this hard to do with bitwise string
operations. But the only reason that bitwise string
operations are so fast is because you can avoid making all of those
jumps into the Perl interpreter; you can hand it both the strings and
an operation, let it groove along in C for awhile, then come back with
an answer.
You can get the same effect with Inline::C.
With a simple substr-based implementation, a C version
is nearly 4 times faster than a nearly identical Perl version:
Benchmark: timing 100000 iterations of csimple3, simple3...
csimple3: 5 wallclock secs ( 4.43 usr + 0.00 sys = 4.43 CPU)
@ 22573.36/s (n=100000)
simple3: 19 wallclock secs (16.90 usr + 0.01 sys = 16.91 CPU)
@ 5913.66/s (n=100000)
Here's the code I used:
#!/usr/bin/perl
use Benchmark;
use Inline C => 'DATA',
VERSION => 0.0,
NAME => 'SimpleTest',
OPTIMIZE => '-O3';
Inline->init;
sub simple3
{
my($a,$b)=@_;
my(@seen);
return undef if (length($a) != length($b));
foreach my $i (0..length($a))
{
my($ac,$bc)=(substr($a,$i,1),substr($b,$i,1));
if ($ac eq $bc)
{
; # Do nothing
}
elsif ($ac eq '_')
{
return undef if (++$seen[$bc] > 1);
}
elsif ($bc eq '_')
{
return undef if (++$seen[$ac] > 1);
}
else { return undef }
}
1;
}
my @tests =
(qw/
_8__3__19
48____7__
_8__3__19
4_2___7__
_8__3__19
4_8___7__
__8_3__19
48____7__
__8_3__19
84____7__
_8__3__19
48_____7_
/
);
sub run_tests
{
my($func,$verbose,@tests)=@_;
my ($s1, $s2);
while (defined($s1 = shift(@tests)))
{
$s2 = shift(@tests);
my $result = $func->($s1, $s2);
print "$s1\n$s2: ",$result?"compatible":"not compatible","\n"
if ($verbose);
}
}
run_tests(\&csimple3, 1, @tests);
timethese(100_000, {
simple3 => sub { run_tests(\&simple3, 0, @tests) },
csimple3 => sub { run_tests(\&csimple3, 0, @tests) },
});
__DATA__
__C__
int csimple3(const char *a, const char *b)
{
int i;
int l;
unsigned char seen[256];
memset(seen,0,256);
if ((l=strlen(a)) != strlen(b))
return 0;
for(i=0;i<l;i++)
{
if (a[i] == b[i])
{
; /* Do nothing */
}
else if (a[i] == '_')
{
if (++seen[b[i]] > 1)
return 0;
}
else if (b[i] == '_')
{
if (++seen[a[i]] > 1)
return 0;
}
else
return 0;
}
return 1;
}