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% --
--
Marvin Humphrey
Rectangular Research ― http://www.rectangular.com

In reply to Re: Determining uniqueness in a string. by creamygoodness
in thread Determining uniqueness in a string. by Yzzyx

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.