If you're gonna get this nuts about speed, you may as well fire up Inline C or XS. If you know XS, this solution is actually easier to grok than some of the more esoteric solutions above, as well as faster:
!/usr/bin/perl
use strict;
use warnings;
# fast_uniq.plx -- 10 unique digits in a 10-char string
use Benchmark qw( cmpthese );
use Inline C => <<'END_C';
/* works for ASCII, EBCDIC, UTF-8 */
int offset;
SV* digits_sv;
void prime_variables (SV* input_sv, SV* zero_sv) {
digits_sv = newSVsv(input_sv);
char* zero_str = SvPV_nolen(zero_sv);
offset = *zero_str;
}
int test_uniq_digits () {
STRLEN digits_len = SvCUR( digits_sv );
char* string = SvPV( digits_sv, digits_len );
char test_buf[10] = { 0,0,0,0,0, 0,0,0,0,0 };
int i, index;
for (i = 0; i < 10; i++) {
index = *string - offset;
if (index < 0 || index > 9)
croak("illegal character: '%c'", *string);
if (test_buf[index] == 1)
return 0;
test_buf[index] = 1;
string++;
}
return 1;
}
END_C
run_test("0123456789", "UNIQUE:\n");
run_test("1123456789", "NOT_UNIQUE:\n");
sub run_test {
my ($digits, $message) = @_;
prime_variables($digits, "0");
print $message;
cmpthese( -5, {
u1 => sub {
for ( 0 .. 9 ) {
return 0 if $digits !~ /$_/;
}
return 1;
},
u1000 => sub { test_uniq_digits },
});
print "\n\n";
}
Here's the output:
UNIQUE:
Rate u1 u1000
u1 10619/s -- -98%
u1000 692527/s 6421% --
NOT_UNIQUE:
Rate u1 u1000
u1 414417/s -- -42%
u1000 712019/s 72% --