My most revered monks,

The subroutine below compute the number of mismatches between two strings (they are always equal) - usually called Hamming Distance.

However my code below is painfully slow. I am terribly in need of a super fast way to do this. In particular it has to process millions of string pairs.

Thus I turn to you my brother monks, for illumination in this matter.
#!/usr/bin/perl -w use strict; my $s1 = 'AAAAA'; my $s2 = 'ATCAA'; my $s3 = 'AAAAA'; hd($s1,s2) # will give value 2 hd($s1,s3) # will give value 0 sub hd { #String length is assumed to be equal my ($k,$l) = @_; my $len = length ($k); my $num_mismatch = 0; for (my $i=0; $i<$len; $i++) { ++$num_mismatch if substr($k, $i, 1) ne substr($l, $i, 1); } return $num_mismatch; }
Update: Benchmark. Thanks so much everybody.
Rate Mine RJ BWK inman Mine 176987/s -- -65% -78% -80% RJ 504123/s 185% -- -38% -44% BWK 817943/s 362% 62% -- -9% inman 901871/s 410% 79% 10% -- *Note: Mine has already included the modification suggested by 'wazoox'.

Regards,
Edward

In reply to Hamming Distance Between 2 Strings - Fast(est) Way? by monkfan

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.