0

I am implementing my own web server. The following method searches for server side includes and builds the html page appropriately.

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;
}

I know StringBuilder is faster than String, but is that all I can do to optimize this? The original data is read into a byte array and converted into a String, at which point it is passed into this method, and the output is converted back into a byte array and sent to the client.

4
  • 2
    Any optimizations you make are probably going to be insignificant compared to disk IO. Have you profiled your code and found this method to be an actual bottleneck? Commented Apr 20, 2013 at 3:21
  • @Supericy No, but I would like to form good code writing habits. Commented Apr 20, 2013 at 3:39
  • 1
    Writing optimized code =/= good code writing habits. Writing readable, maintainable is much more important. Once a piece of code becomes an issue (determined from profiling your application), then would be a good time to go back and revise the problematic areas (and if the optimizations obfuscate the code a lot, make sure to heavily comment it!). Commented Apr 20, 2013 at 3:50
  • @Supericy Your advice is well received. I should probably learn how to use a profiler. :) Commented Apr 20, 2013 at 3:53

1 Answer 1

1

I don't know how significant of an impact this will have, but instead of reading into a byte array and and converting to a String, you can use the IOUtils toString(InputStream) method to read directly to a String. Likewise, you can write the String directly to an OutputStream.

Sign up to request clarification or add additional context in comments.

1 Comment

I will consider this. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.