Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
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 taking refuge in the Monastery: (2)
As of 2014-09-17 01:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (55 votes), past polls