Mem*_*ori 3 java performance search character
这可能看起来有点像一个愚蠢的问题..也许是这样.但是我有一个我经常使用的功能,并且想知道这是否是最快的工作方式.该功能被使用了很多次,以至于任何速度增加实际上都是显而易见的.它只是检查一个字符是否是一个核苷酸(即:如果一个字符是'A','T','C'或'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;
}
Run Code Online (Sandbox Code Playgroud)
这是完成这项工作的最快方式吗?或者您认为值得实现某种索引/地图/其他东西(可能在函数外部执行比较并将此文本复制到代码中的几个位置)?我真的不是Java中这类东西的专家.
最快(但最低内存效率仍然是255字节不错!)将是这样的:
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个这样的函数:
private static boolean isValidNucleotide(char nucleotide) {
/* complexity is just one access to array */
return map[nucleotide];
}
Run Code Online (Sandbox Code Playgroud)
正如@paxdiablo所说,在java中,char是2个字节而不是1个字节,但是你的字符在这个范围内.通过简单地改变return map[nucleotide];,以return map[0x00ff & nucleotide];应工作.
您还可以将地图大小更改为65536安全,避免任何类型的错误.boolean map = new boolean[65536]