Very fast search for specific characters in Java
character, java, performance, search
Solution
Most fastest (but least memory efficient still 255 bytes not bad!) would be like this:
/* this is static member of class */
static boolean map[] = new boolean[256];
static {
for(int j = 0; j < map.length; j++)
map[j] = false;
/* map your required values true here */
map['A'] = true;
map['T'] = true;
map['C'] = true;
map['G'] = true;
/* make small letter here too */
map['a'] = true;
map['t'] = true;
map['c'] = true;
map['g'] = true;
}
Then make a function like this:
private static boolean isValidNucleotide(char nucleotide) {
/* complexity is just one access to array */
return map[nucleotide];
}
As said by @paxdiablo, in java char is 2 bytes not 1 bytes but you characters are within this range. By simply changing `return map[nucleotide];` to `return map[0x00ff & nucleotide];` should work.
You can also change size of map to `65536` to be on safe side and avoid any sort of errors. `boolean map = new boolean[65536]`
Problem
this probably seems like a bit of a silly question.. And maybe it is. But I have a function which I use very frequently and wanted an opinion on if this is the fastest way to do the job. The function is used so many times that any speed increase would actually be noticeable. All it does is check if a character is a nucleotide (ie: if a char is 'A', 'T', 'C', or 'G'. ``` private static boolean isValidNucleotide(char nucleotide) { nucleotide = Character.toUpperCase(nucleotide); if(nucleotide == 'A') return true; if(nucleotide == 'T') return true; if(nucleotide == 'C') return true; if(nucleotide == 'G') return true; return false; } ``` Is this the fastest way to accomplish the job? Or do you think it's worth implementing some kind of index/map/something else (possibly to perform the comparison outside of a function and just copy this text to several spots in the code)? I'm really not an expert on this kind of thing in Java.