Sometime we need to improve the performance of our application into our code. Below are the recommendations for Java code tuning.
- Don’t optimize before you know it’s necessary
- Use a profiler to find the real bottleneck
- Work on the biggest bottleneck first
Managing Objects
- Here, idea is used to use garbage collection less frequently either by canonicalization or by references. Lesser number of garbage collection happens, lesser overhead occurs.
- Avoid creating temporary objects within repeated routines
- Pre-size collection objects
- Better to reuse objects than creating
- Use custom conversion methods for converting data types to reduce creation of temporary objects
- Canonicalize objects (Replacing multiple objects with single object) whenever required and compare by identity
- Replace string and other objects with integer constants and compare by identity
- Better to use primitive types instead of objects for instance variables
- Use StringBuffer than string concatenation operator
- Appropriate use of weak, soft references
- Use cloning to create objects
Best practices for String manipulation
- Avoid internationalization if not required in Strings
- Avoid using Stream Tokenizer
- Use efficient String methods for conversion
- Use concatenation operator for compile time and String Buffers to create String at runtime
- Compare Strings by identity wherever possible
- Differentiate in handling case insensitive and case sensitive comparisons
Loops, switches and Recursion
- Don’t put unwanted and unneeded code within loop
- Move any code that is executed repeatedly with the same result and assign temporary variable before loop
- Avoid using method calls in loops
- Avoid method call in loop termination test
- Prefer to use int data type for loop variable
- Try to use fastest tests in loops
- arraycopy() is to be used for copying arrays than for loop
- Convert equality comparison to identity comparison whenever possible
- Try to use short circuit operator efficiently by putting most common check first
- Eliminate temporary variables from the loop
- Try to use proper switch statement with range values
- Convert recursive method to iterations instead
- Use temporary variables in place of passed parameters to convert a recursive method using a single search path into an iterative method
Managing Sorting and Collection
- Sorting methods are avilable in java.util.Arrays (for arrays of objects) and in java.util.Collections (for objects implementing the Collection interfaces).
- Eliminating casts by specifying data types more precisely.
- Modifying the comparison algorithm to be quicker.
- Replacing the objects with wrappers that compare faster (e.g., java.text.CollationKeys). These are best used when the comparison method requires a calculation for each object being compared, and that calculation can be cached.
- Eliminating methods by accessing fields directly.
- Better to use sorting interface to support the various sorting algorithms
- Use appropriate data structure
- Use appropriate collection class
- Linked list are always better than Arrays when huge insertion and deletion required.
- Check for the classes that are synchronized, it will detoriate the performance especially when we dont need synchronized behavior.
Tuning JDBC
- Use appropriate jdbc drive i.e. recommendation is for type 4 driver
- Avoid the following common mistakes: Failure to close JDBC result sets, statements, and connections.
- Database access is typically very expensive in terms of server resources. Use a connection pool to share database connections efficiently between all requests, but don’t use the JDBC ResultSet object itself as the cache object.
- SQL operation optimization
- Use the prepared statement
- Try to match java type to appropriate data type supported by datanase to avoid overhead.
- For better performance use the store procedure instead of series of SQL queries.
- In metadata queries null argument must be avoided.
- Caching must be used appropriately and cache the data at application level.
Servlet Tuning tips
- SingleThreadModel must be avoided, this has been deprecited in recent version of servlet api.
- Minimize synchronization in Servlets to avoid multiple execution threads becoming effectively single-threaded.
- Do not store large object graphs in javax.servlet.http.HttpSession. Servlets may need to serialize and deserialize HttpSession objects for persistent sessions, and making them large produces a large serialization overhead.
- Use the HttpServlet Init method to perform expensive operations that need only be done once.
- Call HttpSession.invalidate() to clean up a session when you no longer need to use it.
- Use StringBuffer rather than using + operator when you concatenate multiple strings.
- Use the print() method rather than the println() method.
- Use a ServletOutputStream rather than a PrintWriter to send binary data.
- Implement the getLastModified() method to use the browser cache and the server cache.
- Use the application server’s caching facility.
- Session mechanisms from fastest to slowest are: HttpSession, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
- Remove HttpSession objects explicitly in your program whenever you finish the session.
- Set the session time-out value as low as possible.
- Use transient variables to reduce serialization overheads.
- Disable the servlet auto reloading feature.
- Tune the thread pool size.
- Use appropriate logging methodology and minimize amount of data logged.
- Servlet filters are overhead hence use whenever really required.
JSP Tuning tips
- For Web pages that don’t require session tracking, save resources by turning off automatic session creation using: <%@ page session=”false”%>
- Use the jspInit() method to cache static data, and release them in the jspDestroy() method.
- Use the jspInit() method to cache static data.
- Use StringBuffer rather than using + operator when you concatenate multiple strings.
- Use the print() method rather than the println() method.
- Use the include directive instead of the include action when you want to include another page.
- Minimize the scope of the ‘useBean’ action.
- Custom tags incur a performance overhead. Use as few as possible. Especially BodyTags increases overhead.
- Forwards (<jsp:forward>) are better than redirect(sendRedirect) because redirect creats the new request.
- Use the application server’s caching facility, and the session and application objects (using getAttribute()/setAttribute()). There are also third-party caching tags available.
- Session mechanisms from fastest to slowest are: session, Hidden fields, Cookies, URL rewriting, the persistency mechanism.
- Remove ‘session’ objects explicitly in your program whenever you finish the session.
- Reduce the session time-out as low as possible.
- Use ‘transient’ variables to reduce serialization overheads.
- Disable the JSP auto reloading feature.
- Tune the pools in application as per your requirement.
- Avoid serialization of HttpSession, less number of objects in session means high performance
- Validate data on client side to reduce the load on server.