Wednesday, September 23, 2009

Java Performance Optimization Tips & Interview Questions

What are common optimizing practices for a class?


  • Use primitive data types instead of objects as instance variables
  • Keep constructors simple and inheritance hierarchies shallow
  • Avoid initializing instance variable more than once
  • Eliminate unnecessary type casts
  • Enumerators are faster than Iterators due to the specific implementation
  • Ints are the fastest datatypeUse static variables for fields that only need to be assigned once
  • Final classes can be faster
  • Use interfaces, so that the actual underlying data structure can be actually changed without impacting the client program
  • Null out references when they are no longer needed so that gc can collect them when it is running.
  • Avoid character processing using methods like charAt(), setCharAt() methods
  • Use local variables in preference to class variables
  • Compound operators such as n += 4; are faster than n = n + 4; because fewer bytecodes are generated.
  • Shifting by powers of two is faster than multiplying.
  • Multiplication is faster than exponentiation.
  • int increments are faster than byte or short increments.
  • Floating point increments are much slower than any integral increment.
  • It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop.
  • For some applications that access the date a lot, it can help to set the local timezone to be GMT, so that no conversion has to take place.
  • Minimize creation of short-lived objects.
  • Avoid excessive writing to the Java console
  • Minimize the number of JNI calls
  • Avoid unnecessary instanceof operation
  • Avoid using long divides.
  • Persistency adds overheads that make persistent objects slower.
  • Use pipelining and parallelism. Designing applications to support lots of parallel processes working on easily distinguished subsets of the work makes the application faster. If there are multiple steps to processing, try to design your application so that subsequent steps can start working on the portion of data that any prior process has finished, instead of having to wait until the prior process is complete.
  • Use bitshift instead of multiplying or dividing by powers of 2.
  • Scope of variables can impact performance.
  • Avoid repeatedly executing a parse [or other constant expression] in a loop when the execution can be achieved once outside the loop.
  • Use exception only where you need them


How do you optimize methods in a class?

  • Avoid creating temporary objects within frequently called methods
  • Define methods that accept reusable objects to be filled in with data, rather than methods that return objects holding that data.
  • Use methods that alter objects without making copies
  • Eliminate repeatedly called methods where alternatives are possible [For example, if you are processing a vector in a loop, get the size of the vector in the beginning in a length local variable rather than calling size() method on the vector in the condition part of the for loop]
  • Use private and static methods and final classes to encourage inlining by the compiler
  • Inline methods manually where it is appropriate
  • Keep methods short and simple to make them automatic inlining candidates
  • Access to private member by the inner classes to the enclosing class goes by a method call even if it is not intended to.
  • Keep synchronized methods out of loops if you possibly can.


How do you optimize loops and conditional statements?

  • Reduce the number of temporary objects being used,especially in loops.
  • Use short-circuit Boolean operators instead of normal Boolean operators
  • Eliminate unnecessary repeated method calls from loops
  • Move loop invariants outside the loop.
  • Perform the loop backwards (this actually performs slightly faster than forward loops do). [Actually it is converting the test to compare against 0 that makes the difference].
  • It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop.
  • Use exception terminated infinite loops for long loops.
  • Whatever can be calculated outside of a loop should be calculated outside of the loop.
  • For multidimensional arrays store a reference for the currently accessed row in a variable.
  • Cache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection.size().


How do you optimize Strings?

  • Use StringBuffer instead of String concat ‘+’ operator
  • Formatting numbers using java.text.DecimalFormat is always slower than Double.toString(double) method, because internally java.text.DecimalFormat() calls
  • Double.toString(double) then parses and converts the results.
  • Convert String to char[] arrays to process characters rather than accessing one at a time using String.charAt() method
  • Creating Double from string is slow
  • Intern() Strings to enable (==) comparisions
  • Use char arrays for all character processing in loops, rather than using String or StringBuffer classes
  • Set the initial string buffer size to maximum if it known.
  • StringTokenizer is very inefficient, and can be optimized by storing the string and delimiter in a character array instead of in String
  • DON’T create static strings via new().
  • Where the compiler cannot resolve concatenated strings at compile time, the code should be converted to StringBuffer appends, and the StringBuffer should be appropriately sized rather than using the default size.
  • The compiler concatenates strings where they are fully resolvable, so don t move these concatenations to runtime with StringBuffer.


How do you optimize arrays, vectors and collections?

  • Create copies of simple array by initializing them through loops or by using System.arraycopy(), create copies of complex arrays by cloning them
  • Iterator.hasNext() and Enumerator.hasMoreElements() need not be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead.
  • ArrayList is faster than Vector
  • Go for a non-synchronized version of collection unless used in a threaded application
  • LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup
  • Accessing arrays is much faster than accessing vectors, String, and StringBuffer
  • Vector is convenient to use, but inefficient. Ensure that elementAt() is not used inside a loop.
  • Re-use Hashtables by using Hashtable.clear().
  • Removing elements from a Vector will necessitate copying within the Vector if the element is removed from anywhere other than the end of the collection.
  • Presizing collections to the expected size is more efficient than using the default size and letting the collection grow.
  • For multidimensional arrays store a reference for the currently accessed row in a variable.
  • When adding multiple items to a collection, add them all in one call if possible.



How do you optimize threads?

  • Avoid synchronization where possible
  • Code a multi-thread for multi-processor machine.
  • Synchronizing on method rather than code blocks is slightly faster
  • Polling is only acceptable when waiting for outside events and should be performed in a "side" thread. Use wait/notify instead.
  • Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly.
  • Keep synchronized methods out of loops if you possibly can.
  • Maximize thread lifetimes and minimize thread creation/destruction cycles.
  • Use Thread pools where these improve performance.
  • Use Thread.sleep() instead of a for loop for measured delays.
  • Use a separate timer thread to timeout socket operations
  • Use more server threads if multiple connections have high latency.


How do you optimize IO?
  • Use Buffered IO classes
  • File information such as file length requires a system call and can be slow… Don’t use it often. Similarly, System.currentTimeMillis() uses a native call to get current time. Make sure your production code does not have this statement.
  • Many java.io.File methods are system calls which can be slow
  • Use BufferedIO streams to access URLConnection sInput/Output streams.
  • Use the transient keyword to define fields to avoid having those fields serialized. Examine serialized objects to determine which fields do not need to be serialized for the application to work.
  • Increase server listen queues for high load or high latency servers.


How do you optimize exceptions?

  • Be specific while handling the exception in your catch block.
  • Be specific while throwing exception in your throws clause.
  • Do not use Exception Handling to control programming flow.
  • Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly.
  • Always use the finally block to release the resources to prevent resource leaks.
  • Handle exceptions locally wherever possible.
  • Do not use Exception handling in loops.


How will you optimize performance in JDBC?

  • Use batch transactions.
  • Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
  • Use PreparedStatement when you execute the same statement more than once.
  • Use CallableStatement when you want result from multiple and complex statements for a single request.
  • Use batch update facility available in Statements.
  • Use batch retrieval facility available in Statements or ResultSet.
  • Set up proper direction for processing rows.
  • Use proper getXXX() methods.
  • Close ResultSet, Statement and Connection whenever you finish your work with them.
  • Write precise SQL queries.
  • Cache read-only and read-mostly tables data.
  • Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.


How do you optimize servlets?

  • 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.


How do you optimize a JSP page?


  • Use jspInit() 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 instead of JSPWriter to send binary data
  • Initialize the 'out' object (implicit object) with proper size in the page directive.
  • Flush the data partly
  • Minimize code in the synchronized block
  • Set the content length
  • Release resources in jspDestroy() method.
  • Give 'false' value to the session in the page directive to avoid session object creation.
  • Use include directive instead of include action when you want to include the child page content in the translation phase.
  • Avoid giving unnecessary scope in the 'useBean' action.
  • Do not use custom tags if you do not have reusability.
  • Use application server caching facility
  • Use Mixed session mechanisms such as 'session' with hidden fields
  • Use 'session' and 'application' as cache.
  • Use caching tags provided by different organizations like openSymphony.com
  • Remove 'session' objects explicitly in your program whenever you finish the taskReduce session time out value as much as possible
  • Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
  • Disable JSP auto reloading feature.
  • Use thread pool for your JSP engine and define the size of thread pool as per application requirement.



What are common optimizing practices for EJB?

  • Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server.
  • Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server.
  • Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate.
  • Make coarse grained session and entity beans to reduce network calls.
  • Control serialization by modifying unnecessary data variables with 'transient' key word to avoid unnecessary data transfer over network.Cache EJBHome references to avoid JNDI lookup overhead.
  • Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions.
  • Set proper transaction age(time-out) to avoid large transaction.
  • Use clustering for scalability.
  • Tune thread count for EJB Server to increase EJB Server capacity.
  • Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean.
  • Choose best EJB Server by testing with ECperf tool kit.
  • Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread safe, client state etc..


How do you optimize stateless session beans?

  • Tune the Stateless session beans pool size to avoid overhead of creation and destruction of beans.
  • Use setSessionContext() or ejbCreate() method to cache bean specific resources.
  • Release acquired resources in ejbRemove() method


How do you optimize stateful session beans?

  • Tune Stateful session beans cache size to avoid overhead of activation and passivation process.
  • Set optimal Stateful session bean age(time-out) to avoid resource congestion.
  • Use 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead.
  • Remove Stateful session beans explicitly from client using remove() method.


How do you optimize entity beans?

  • Tune the entity beans pool size to avoid overhead of creation and destruction of beans.
  • Tune the entity beans cache size to avoid overhead of activation, passivation and database calls.
  • Use setEntityContext() method to cache bean specific resources.
  • Release acquired resources in unSetEntityContext() method
  • Use Lazy loading to avoid unnecessary pre-loading of child data.
  • Choose optimal transaction isolation level to avoid blocking of other transactional clients.
  • Use proper locking strategy.
  • Make read-only entity beans for read only operations.
  • Use dirty flag to avoid unchanged buffer data updation.
  • Commit the data after the transaction completes to reduce database calls in between transaction.
  • Do bulk updates to reduce database calls.
  • Use CMP rather than BMP to utilize built-in performance optimization facilities of CMP.
  • Use ejbHome() methods for global operations.
  • Tune connection pool size to reduce overhead of creation and destruction of database connections.
  • Use JDBC tuning techniques in BMP.
  • Use direct JDBC rather than using entity beans when dealing with huge data such as searching a large database.
  • Use business logic that is specific to entity bean data.


How do you optimize message driven beans?

  • Tune the Message driven beans pool size to promote concurrent processing of messages.
  • Use setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources.
  • Release acquired resources in ejbRemove() method.
  • Use JMS tuning techniques in Message driven beans.


How do you optimize Java Message Service (JMS)?


  • Start producer connection after you start consumer.
  • Use concurrent processing of messages.
  • Close the Connection when finished.
  • Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE.
  • Control transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages.
  • Close session object when finished.
  • Make Destination with less capacity and send messages accordingly.
  • Set high Redelivery delay time to reduce network traffic.
  • Set less Redelivery limit for reducing number of message hits.
  • Choose non-durable messages wherever appropriate to avoid persistence overhead.
  • Set optimal message age (TimeToLive value).
  • Receive messages asynchronously.
  • Close Producer/Consumer when finished.
  • Choose message type carefully to avoid unnecessary memory overhead.
  • Use 'transient' key word for variables of ObjectMessage which need not be transferred.


-----
Please check with Manuals. Author is NOT responsible for any misinformation / incorrect information or typographical errors.


NOTE: If you would like to share any useful info, please mail to the authors.

No comments:

Post a Comment

Happy Reading!

Ganex Improves .. Headline Animator