簡體   English   中英

非常快速地搜索Java中的特定字符

[英]Very fast search for specific characters in Java

這可能看起來有點像一個愚蠢的問題..也許是這樣。 但是我有一個我經常使用的功能,並且想知道這是否是最快的工作方式。 該功能被使用了很多次,以至於任何速度增加實際上都是顯而易見的。 它只是檢查一個字符是否是一個核苷酸(即:如果一個字符是'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;
}

這是完成這項工作的最快方式嗎? 或者您認為值得實現某種索引/地圖/其他東西(可能在函數外部執行比較並將此文本復制到代碼中的幾個位置)? 我真的不是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;
}

然后創建一個這樣的函數:

private static boolean isValidNucleotide(char nucleotide) {
    /* complexity is just one access to array */
    return map[nucleotide];
}

正如@paxdiablo所說,在java中,char是2個字節而不是1個字節,但是你的字符在這個范圍內。 通過簡單地改變return map[nucleotide]; return map[0x00ff & nucleotide]; 應該管用。

您還可以將地圖大小更改為65536以確保安全,避免任何類型的錯誤。 boolean map = new boolean[65536]

您可以嘗試使用switch-case ,它通常用作小型交換機的表查找:

switch(nucleotide) {
case 'A':
case 'T':
case 'C':
case 'G':
    return true;
}
return false;

請注意,如果經常調用JVM的JIT,它可能會使基於if的代碼非常快。

擺脫Character.toUpperCase並檢查大寫和小案例,它將顯着加快你的功能。

private static boolean isValidNucleotide(char nucleotide) {       
    if(nucleotide == 'A' || nucleotide == 'a') return true; 
    // Rest of your conditions

    return false;
}

我用你的原始函數進行了一個小測試,平均花費80 ms來執行10000000 times但是當我刪除了Character.toUpperCase()並明確檢查兩種情況時它只用了40 ms ,這是一個顯着的改進。

編輯:

使用@Shivam建議的Map解決方案Kalra平均只用了11 ms

我沒有嘗試過,但您可以嘗試使用Regex查看性能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM