【问题标题】:How can I optimize this String search/replace method?如何优化此字符串搜索/替换方法?
【发布时间】:2013-04-13 12:36:09
【问题描述】:

我正在实现自己的网络服务器。以下方法搜索服务器端包含并适当构建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 比 String 快,但我能做的就是优化它吗?将原始数据读入字节数组并转换为String,此时将其传递给该方法,并将输出转换回字节数组并发送给客户端。

【问题讨论】:

  • 与磁盘 IO 相比,您所做的任何优化都可能微不足道。您是否分析过您的代码并发现此方法是一个实际的瓶颈?
  • @Supericy 没有,但我想养成良好的代码编写习惯。
  • 编写优化代码 =/= 良好的代码编写习惯。编写可读、可维护的代码更为重要。一旦一段代码成为问题(通过分析您的应用程序确定),then 将是返回并修改有问题的区域的好时机(如果优化使代码混淆了很多,请确保强烈评论它!)。
  • @Supericy 你的建议很受欢迎。我可能应该学习如何使用分析器。 :)

标签: java string search optimization replace


【解决方案1】:

我不知道这会产生多大的影响,但是您可以使用IOUtils toString(InputStream) 方法直接读取到字符串,而不是读取字节数组并转换为字符串。同样,您可以write the String directly to an OutputStream

【讨论】:

  • 我会考虑的。谢谢。
猜你喜欢
  • 2014-07-12
  • 2020-01-06
  • 2011-10-23
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多