Servlet Performance Tips

This document contains tips for writing faster servlets.

  • Use the request's ServletOutputStream rather than its PrintWriter when you can because it avoids the extra character conversion overhead. The print and println convenience methods are in both types of output. In other words, use getOutputStream() rather than getWriter(). However, if you are outputting data with a character set other than ISO-8859-1, then you will still need to use the PrintWriter.
  • Writing byte arrays are much faster than "print"ing strings. Watch out for the extra memory overhead, though, of calling the string's getBytes method. When using a byte array like this, it is not always necessary to call this method each time the string is to be printed. The array can instead be cached in the servlet's init method, and then freed in its destroy method.
  • If a parameter value is to be used more than once or twice, then avoid the overhead of calling getParameter multiple times. Instead, cache the value. For example:
    String param = req.getParameter("myparam");
    
    // ...Use param multiple times...
  • Reduce memory consumption by writing strings individually, rather than concatenating them first. This does not apply to concatenating constant strings because the Java compiler already does this for you. For example, this is okay:
    out.print("One" + " Two"
              + " Three");
    but this will consume more memory:
    out.print("Value is " + someValue + ". So there");
    The following is equivalent, and will consume less memory:
    out.print("Value is ");
    out.print(someValue);
    out.print(". So there.");
  • If you need to concatenate only two strings, then use the concat(String) method instead of the '+' operator. For example, use
    String s = "Hello, ".concat(name);
    instead of
    String s = "Hello, " + name;
    This avoids creating a new StringBuffer object.
  • In order for persistent connections to work effectively, the content length must be set so that one side knows when the other is finished sending data. Setting the content length whenever it is known may improve performance by decreasing the number of connections a client needs to make to the server.
  • If it is known that the output is encoded strictly with the ISO-8859-1 character set, then outputting single characters with write instead of print is slightly faster. For example,
    out.write('.');

    vs.

    out.print('.');
    Furthermore, printing single characters using strings is slower than printing them as char values. For example,
    out.print('.');

    vs.

    out.print(".");
  • If a servlet handles form data that affects page content, an author will often use the servlet to generate the entire page. The dynamic content may be only a small portion of the document, however, and the servlet will spend a significant amount of time outputting static content. One option is to place the dynamic data into its own frame whose content is served by the servlet, and the static data into another frame served by an ordinary URL. The static part may even include form controls, but this can still be placed into an ordinary HTML file.

    (See Working With Frames and Servlets.)

  • If you override the init() method when creating a subclass of HttpServlet or GenericServlet, then call super.init() at the start of the method. This will cause the servlet startup to be recorded in the log.
  • Fields do not need to be initialized to their default values. Java guarantees that when the class or object is created, each field will hold a well-defined default value. Objects will default to null, numbers to zero, and Boolean values to false. For example, these statements are redundant:
    private Object myObj = null;
    private int count = 0;
    private boolean flag = false;
    They are exactly equivalent to:
    private Object myObj;
    private int count;
    private boolean flag;

Useful Performance Links

  • Best Practices to improve performance in Servlets from PreciseJava

    Key Points

    • Use init() method to cache static data
    • Use StringBuffer rather than using + operator when you concatenate multiple strings
    • Use print() method rather than println() method
    • Use ServletOutputStream rather than PrintWriter to send binary data
    • Initialize the PrintWriter with proper size
    • Flush the data partly
    • Minimize code in the synchronized block
    • Set the content length
    • Release resources in destroy() method.
    • Implement getLastModified() method to use browser cache and server cache
    • Use application server caching facility
    • Use Mixed session mechanisms such as HttpSession with hidden fields
    • Remove HttpSession objects explicitly in your program whenever you finish the task
    • Reduce session time out value as much as possible
    • Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
    • Disable servlet auto reloading feature.
    • Use thread pool for your servlet engine and define the size as per application requirement.

  • Servlet and JSP performance tips from Java Performance Tuning
  • Servlet Programming Tips from CoolServlets.com