2011-07-19 38 views
1

我是一個半經驗豐富的程序員,只是沒有這麼多的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的最佳實踐。

+1

使用dictionaryLine作爲StringBuilder而不僅僅是一個String。 –

回答

0

通常,您通過創建和丟失較少的對象來減少垃圾收集活動。有很多地方可以生成對象:

  1. 您正在閱讀的每行都會生成一個字符串。
  2. 字符串是不可變的,所以可能會有更多的對象在generate()函數中產生。

如果你正在處理大量的字符串,考慮StringBuilder,這是一個可變的字符串生成器,從而減少垃圾。

但是,100ms的垃圾回收還不錯,尤其是在手機設備上。

0

基本上,你的方式很糟糕,因爲對於每個詞典單詞,你都會爲所有混亂的字符串生成所有可能的組合,yikes!如果您有足夠的內存,只需爲所有單詞生成所有組合,並將每個組合與每個字典值進行比較。

但是,必須假定沒有足夠的內存,在這種情況下,這會變得更加複雜。你可以做的是用一個char []來產生一個爭奪的可能性,測試它,重新排列緩衝區中的字符,測試,重複等,直到所有的可能性都被耗盡。