我正在實施我自己的網絡服務器。以下方法搜索服務器端包含並適當地構建html頁面。如何優化此字符串搜索/替換方法?
public String getSSI(String content) throws IOException {
String beginString = "<!--#INCLUDE VIRTUAL=\"";
String endString = "\"-->";
int beginIndex = content.indexOf(beginString);
while (beginIndex != -1) {
int endIndex = content.indexOf(endString, beginIndex);
String includePath = content.substring(beginIndex+beginString.length(), endIndex);
File includeFile = new File(BASE_DIR+includePath);
byte[] bytes = new byte[(int) includeFile.length()];
FileInputStream in = new FileInputStream(includeFile);
in.read(bytes);
in.close();
String includeContent = new String(bytes);
includeContent = getSSI(includeContent);
content = content.replaceAll(beginString+includePath+endString, includeContent);
beginIndex = content.indexOf(beginString);
}
return content;
}
我知道的StringBuilder比字符串快,但就是我所能做的優化呢?原始數據被讀入一個字節數組並轉換成一個字符串,此時它被傳遞到這個方法中,並且輸出被轉換回一個字節數組併發送到客戶端。
與磁盤IO相比,您所做的任何優化都可能不重要。你有沒有分析你的代碼,發現這種方法是一個實際的瓶頸? – Supericy 2013-04-20 03:21:30
@Supericy不,但我想要形成良好的代碼書寫習慣。 – BLuFeNiX 2013-04-20 03:39:41
編寫優化的代碼=/=良好的代碼書寫習慣。書寫易讀,可維護更重要。一旦一段代碼成爲一個問題(通過分析應用程序確定),那麼*然後*是返回並修改問題區域的好時機(如果優化混淆了很多代碼,請務必對其進行嚴重評論! )。 – Supericy 2013-04-20 03:50:44