2011-03-16 37 views
1

這是我的問題。我在我的遊戲中爲我的Gui製作了一個TextBox。幫助優化該指數行列,反之亦然算法

它的功能是每當我調整它的大小時,因爲它包含了換行符,我必須弄清楚插入符號在文本字符串中的位置,然後我需要在reize之後將其轉換爲適當的行列。根據我的分析器最慢的部分是當我得到下一個Unicode字符評估:

int AguiTextBox::indexFromColumnRow(int column, int row, bool includeUnwantedChars) const 
    { 
     size_t rowLen = 0; 

     int retIndex = -1; 
     int bytesSkipped = 0; 
     int curCharLen = 0; 
     std::string curChar; 

     std::string::const_iterator it = getText().begin(); 
     std::string::const_iterator end = getText().end(); 


     //decrement column so that the lowest is -1 
     column--; 
     if(textRows.size() == 0 || (column == -1 && row == 0)) 
     { 
      //not in the text 
      return -1; 
     } 
0.01s  for(size_t i = 0; i < textRows.size(); ++i) 
     { 
      //get length of row 
0.00s   rowLen = _unicodeFunctions.getUtf8StringLength(textRows[i]); 

      //handle -1th case 

      //get next character 
      do 
      { 
0.00s    curCharLen = _unicodeFunctions.bringToNextUnichar(it,end); 
0.01s    curChar = getText().substr(bytesSkipped,curCharLen); 
       bytesSkipped += curCharLen; 
       if(includeUnwantedChars) 
        retIndex++; 
      } while (curChar[0] >= 0 && curChar[0] < ' ' && curChar != "\n"); 

      if(!includeUnwantedChars) 
      retIndex++; 

      //only increase for newlines 
0.00s   if(curChar != "\n") 
      { 
       bytesSkipped -= curCharLen; 
       retIndex--; 
       it -= curCharLen; 
      } 

      if((int)i == row && column == -1) 
      { 
       return retIndex; 
      } 


0.06s   for(size_t j = 0; j < rowLen; ++j) 
      { 
       //get next character 
       do 
       { 
0.10s     curCharLen = _unicodeFunctions.bringToNextUnichar(it,end); 
0.91s     curChar = getText().substr(bytesSkipped,curCharLen); 
0.03s     bytesSkipped += curCharLen; 

0.03s     if(includeUnwantedChars) 
         retIndex++; 

0.11s    } while (curChar[0] >= 0 && curChar[0] < ' ' && curChar != "\n"); 

0.06s    if(!includeUnwantedChars) 
0.00s     retIndex++; 

0.02s    if((int)i == row && (int)j == column) 
       { 
        return retIndex; 
       } 
      } 
     } 

     return retIndex; 
    } 

我怎麼能優化這個?

謝謝

@Erik是什麼意思關於字符雙端隊列?

回答

1

你提取的子帶:

curChar = getText().substr(bytesSkipped,curCharLen); 

但你只使用第一個元素。您可以通過簡單地提取您需要的char避免串建築/複印。

關於通用算法優化 - 我會花費構建字符對象的deque所需的資源,而不是使用std::string。這會讓你直接索引任何字符,不需要重複掃描和解析相同的utf-8序列。

+0

你能詳細介紹一下出列的想法嗎? – jmasterx 2011-03-16 01:54:50

+0

@Milo:這取決於你的其他代碼。如果你有一個1000字節的字符串,以評估800個字符,您目前調整大小時解析字節轉換成字符一遍又一遍。建立一個只解析用戶*類型*並保留的系統平行的* utf8字節*和*字符*可以避免重複的解析 – Erik 2011-03-16 08:42:26