Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: simple string comparison for efficiency

by GrandFather (Cardinal)
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]/; }

Prints:

ATGNCNC eq ATGACNN ATGNCNC ne TTGACNN

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


Comment on Re: simple string comparison for efficiency
Select or Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (14)
As of 2014-07-24 20:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (167 votes), past polls