Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: simple string comparison for efficiency

by GrandFather (Saint)
on May 28, 2009 at 21:05 UTC ( #766750=note: print w/replies, xml ) Need Help??

in reply to simple string comparison for efficiency

Tell us about the larger picture. There is likely to be room for improving whatever you are doing at present, or at least for us to target solutions to whatever the bigger problem is. Most gains in performance are not obtained by micro-optimizations such as you are asking for. Some tricks that will give huge performance gains in some situations will cripple the code in other situations.

That said, you can build masks then xor the strings to give something like the fast match you are looking for where the strings to be matched are fairly long. Consider:

use strict; use warnings; my $strA = 'ATGNCNC'; my $strB = 'ATGACNN'; my $strC = 'TTGACNN'; print $strA, (match ($strA, $strB) ? ' eq' : ' ne'), " $strB\n"; print $strA, (match ($strA, $strC) ? ' eq' : ' ne'), " $strC\n"; sub match { my ($mask1, $mask2) = @_; my ($str1, $str2) = @_; $mask1 =~ tr/NATGC/0\xFF/; $mask2 =~ tr/NATGC/0\xFF/; $mask1 &= $mask2; $str1 ^= $str2; $str1 &= $mask1; return $str1 !~ /[^\x00]/; }



If you can cache the masks (say you were matching all strings against all others for example) then you get a greater gain.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: simple string comparison for efficiency
by CaptainF (Initiate) on May 29, 2009 at 00:16 UTC
    Grandfather, your solution using bitwise operators would not have occurred to me, but was exactly what I needed. It solved the problem several orders of magnitude faster than my solution. Is there a simple way to extract the number of string positions where one or both strings had an 'N' from your code?

      Add the line:

      my $nCount = ($mask1 =~ tr/N//) + ($mask2 =~ tr/N//);

      as the third line of sub match.

      True laziness is hard work

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://766750]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2023-02-01 21:19 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (14 votes). Check out past polls.