簡體   English   中英

JAVA-加速代碼

[英]JAVA - Speed up the code

我想加快我的代碼。 快速狀態信息:

  • 有一個以上的列表( String ),如_list1_list2_list3

  • 我嘗試在這些列表中找到一個單詞( String )。

  • 如果找到一個單詞,我將使用列表中單詞的索引。

這是我的代碼:

private static int foundIndex (String s) 
{
    if (_list1.contains(s)) {
        return _list1.indexOf(s);
    } else if (_list2.contains(s)) {
        return _list2.indexOf(s);
    } else if (_list3.contains(s)) {
        return _list3.indexOf(s);
    } else if (_list4.contains(s)) {
        return _list4.indexOf(s);
    }
...
...
...
...
    } else if (_list100.contains(s)) {
        return _list100.indexOf(s);
    }
    return -1;
}

如何加快我的代碼?

我想到了幾個簡單的優化方法:

1.用if (i = indexOf(s) >= 0) return i替換if (contains) then indexOf模式if (i = indexOf(s) >= 0) return i

2.添加查找數據結構(例如Map<String,Integer>並在列表中添加或更改列表時使用它來代替列表或通過更新它來添加列表

List<String>添加所有列表( String )並對其進行迭代:

private static int foundIndex (String s) {
   for (String currentList : lists){
       int indexOf = currentList.indexOf(s);
       if (indexOf != -1) {
          return indexOf;
       }
    }
    return -1;
}

我將代碼的算法更改為您的建議。 我以前曾使用過list,現在更改了它。 我使用2D字符串數組。 但是代碼性能卻下降了157%。

新代碼:

private static String[][] _lists = new String[200][100];

private static int foundIndex (String s) {
for (int i = 0; i < 200; i++) {
        for (int j = 0; j < 100; j++) {
            if (_lists[i][j].equals(s) == true) {
                return j;
            }
        }
    }
    return -1;
}

那就是問題開始的地方。

如果我要查找的代碼是“ _list [180] [?]”,則很難找到它。

如何加快我的代碼?

謝謝。

暫無
暫無

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

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