我是一個半經驗豐富的程序員,只是沒有這麼多的Java。爲了幫助學習Java/Android,我開始編寫一個世界構建器應用程序,這個應用程序需要2-7個字符,並找出所有常見的詞彙。目前,我有大約10,000個單詞分爲26個.txt文件,這些文件是根據用戶輸入的字符加載的。它們共有〜10kb的數據。Android垃圾收集器慢下來
邏輯很簡單,但現在,GC似乎在放慢一切,我努力尋找方法來優化,因爲我缺乏Java的經驗。這裏是下面的代碼,我幾乎是GC是持續運行的。我想用2-4個字符指出下面的代碼運行速度非常快。比這更大的東西變得非常慢。
public void readFile() throws IOException, NotFoundException
{
String dictionaryLine = new String(); //Current string from the .txt file
String currentString = new String(); //Current scrambled string
String comboStr = new String(); //Current combo string
int inputLength = myText.getText().length(); // lenth of the user input
//Loop through every "letter" dictionary
for(int z = 0; z < neededFiles.length - 1; z++)
{
if(neededFiles[z] == null)
break;
InputStream input = neededFiles[z];
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(inputReader, inputLength);
//Loop through every line in the dictionary
while((dictionaryLine = reader.readLine()) != null)
{
Log.i(TAG, "dictionary: " + dictionaryLine);
//For every scrambled string...
for(int i = 0; i < scrambled.size(); i++)
{
currentString = scrambled.get(i).toString();
//Generate all possible combos from the scrambled string and populate 'combos'
generate(currentString);
//...lets find every possible combo from that current scramble
for(int j = 0; j < combos.size(); j++)
{
try
{
comboStr = combos.get(j).toString();
//If the input length is less than the current line, don't even compare
if(comboStr.length() < dictionaryLine.length() || comboStr.length() > dictionaryLine.length())
break;
//Add our match
if(dictionaryLine.equalsIgnoreCase(comboStr))
{
output.add(comboStr);
break;
}
}
catch(Exception error)
{
Log.d(TAG, error.getMessage());
}
}
combos.clear();
}
}
}
}
爲了幫助澄清這一代碼生成以下的很多,很多臺詞:
GC_FOR_MALLOC freed 14000 objects/510000 byes in 100ms
我感謝所有幫助你可以給,即使它只是Java的最佳實踐。
使用dictionaryLine作爲StringBuilder而不僅僅是一個String。 –