How Synchronization impacts performance

  • Avoid synchronization where possible.
  • ArrayList is faster than Vector
  • Only List and Map have efficient thread-safe implementations: the Vector and Hashtable classes respectively.
  • Synchronized methods are slower than the identical non-synchronized one.
  • Consider using non-synchronized classes and synchronized-wrappers.
  • FastVector is faster than Vector by making the elementData field public, thus avoiding (synchronized) calls to elementAt().
  • Use threads. Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly.
  • use methods in order: static > final > instance > interface > synchronized
  • Because synchronization synchronizes thread memory with main memory, there is a cost to synchronization beyond simply acquiring a lock.
  • Make synchronized blocks as short as possible.
  • Spread synchronizations over more than one lock.
  • Minimizing synchronization may take work, but can pay off well.
  • Minimize the synchronized block in the service method.
Advertisements

How to improve Servlet performance

  • Use the servlet init() method to cache static data, and release them in the destroy() method.
  • 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.
  • Initialize the PrintWriter with the optimal size for pages you write.
  • Flush the data in sections so that the user can see partial pages more quickly.
  • Minimize the synchronized block in the service method.
  • 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.

How to Improve JSP Page performance

  • 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 a ServletOutputStream rather than a PrintWriter to send binary data.
  • Initialize the PrintWriter with the optimal size for pages you write.
  • Flush the data in sections so that the user can see partial pages more quickly.
  • Minimize the synchronized block in the service method.
  • Avoid creating a session object with the directive <%@ page session=”false” %>
  • Increase the buffer size of System.out with the directive <%@ page buffer=”12kb” %>
  • 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.
  • 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 thread pool size.

Design Patterns : Performance

  • use the flyweight pattern to reduce object creation [The flyweight pattern uses a factory instead of ‘new’ to reuse objects rather than always create new ones].
  • The Singleton pattern and the Flyweight (object factory) pattern are useful to limit numbers of objects of various types and to assist with object reuse and reduce garbage collection.
  • Use the Data Access Object pattern to decouple business logic from data access logic, allowing for optimizations to be made in how data is managed.
  • Use the Fast-Lane Reader pattern to accelerate read-only data access by not using enterprise beans.
  • Use the Front Controller pattern to centralize incoming client requests, allowing optimizations to be made in aggregating the resulting view.
  • Use the Front Controller pattern to channel all client requests through a single decision point, which allows the application to be balanced at runtime.
  • Use the Page-by-Page Iterator pattern to efficiently access a large, remote list by retrieving its elements one sublist of value objects at a time.
  • Use the Session Facade pattern to provide a unified, workflow-oriented interface to a set of enterprise beans, thus minimizing client calls to server EJBs.
  • Use a Session Facade to provide a simple interface to a complex subsystem of enterprise beans, and to reduce network communication requirements
  • Use the Value Object pattern to efficiently transfer remote, fine-grained data by sending a coarse-grained view of the data.
  • Use the factory pattern to enable reuse or cloning of objects
  • The Abstract Factory design pattern uses a single class to create more than one kind of object.
  • An alternative to the Flyweight pattern is the Prototype pattern, which allows polymorphic copies of existing objects. The Object.clone() method signature provides support for the Prototype pattern.
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. Then you could keep already-initialized objects in a table, and clone an existing object instead of expensively creating a new one from scratch.
  • Immutable objects can be returned directly when using Prototyping, avoiding the copying overhead.
  • Combine multiple remote calls for state information into one call using a value object to wrap the data (the Value Object pattern, superceded by local interfaces in EJB 2.0).
  • Where long lists of data are returned by queries, use the Page-by-Page Iterator pattern: a server-side object that holds data on the server and supplies batches of results to the client.
  • When the client would request many small data items which would require many remote calls to satisfy, combine the multiple calls into one call which results in a single Value Object which holds all the data required to be transferred. Use the Value Object to send a single coarse-grained object from the server to the client(s).
  • For read-only access to a set of data that does not change rapidly, use the Fast Lane Reader pattern which bypasses the EJBs and uses a (possibly non-transactional) data access object which encapsulates access to the data. Use the Fast Lane Reader to read data from the server and display all of them in one shot.
  • Wrap multiple entity beans in a session bean to change multiple EJB remote calls into one session bean remote call and several local calls (pattern called SessionFacade).
  • Cache EJBHome references to avoid JNDI lookup overhead (pattern called ServiceLocator).
  • The ServiceLocator/EJBHomeFactory Pattern reduces the expensive JNDI lookup process by caching EJBHome objects.
  • The SessionFacade Pattern reduces network calls by combining accesses to multiple Entity beans into one access to the facade object.
  • The MessageFacade/ServiceActivator Pattern moves method calls into a separate object which can execute asynchronously.
  • The ValueObject Pattern combines remote data into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data.
  • The ValueObjectFactory/ValueObjectAssembler Pattern combines remote data from multiple remote objects into one serializable object, thus reducing the number of network transfers required to access multiple items of remote data.
  • The ValueListHandler Pattern: avoids using multiple Entity beans to access the database, using Data Access Objects which explicitly query the database; and returns the data to the client in batches (which can be terminated) rather than in one big chunk, according to the Page-by-Page Iterator pattern.
  • The CompositeEntity Pattern reduces the number of actual entity beans by wrapping multiple java objects (which could otherwise be Entity beans) into one Entity bean.
  • The Recycler pattern fixes only the broken parts of a failed object, to minimize the replacement cost.
  • Use a factory class instead of directly calling the “new” operator, to allow easier reuse of objects.
  • Instead of making lots of remote requests for data attributes of an object, combine the attributes into another object and send the object to the client. Then the attributes can be queried efficiently locally (this is called the Value Object pattern). Consider caching the value objects where appropriate.
  • The Proxy design pattern
    • Using a proxy, you can delay image loading until the image is required.
    • The Proxy pattern often instantiates its real object, the Decorator pattern (which can also use proxy objects) rarely does.
    • The java.lang.reflect package provides three classes to support the Proxy and Decorator patterns: Proxy, Method, and InvocationHandler.

How to Improve the Java JDBC Performance

  • Use prepared statements. Use parametrized SQL.
  • Tune the SQL to minimize the data returned (e.g. not ‘SELECT *’).
  • Minimize transaction conflicts (e.g. locked rows).
  • Use connection pooling.
  • Try to combine queries and batch updates.
  • Use stored procedures.
  • Cache data to avoid repeated queries.
  • Close resources (Connections, Statements, ResultSets) when finished with.
  • Select the fastest JDBC driver.
  • If you are not using stored procedures or triggers, turn off autocommit. All transaction levels operate faster with autocommit turned off, and doing this means you must code commits.
  • Use connection pooling, either explicitly with your own implementation, or implicitly via a product that supports connection pooling.
  • Use batch updates (sending multiple rows to the database in one call).
  • Use the type-correct get() method, rather than getObject().
  • Avoid n-way database joins: every join has a multiplicative effect on the amount of work the database has to do. The performance degradation may not be noticeable until large datasets are involved.
  • Avoid bringing back thousands of rows of data: this can use a disproportionate amount of resources.
  • Run an application server and any database servers on separate server machines.
  • One of the most time-consuming procedures of a database application is establishing a connection to the database. Use connection pooling to minimize this overhead
  • Use the same connection to execute multiple statements
  • Avoid distributed transactions (transactions that span mutliple connections).
  • Use scrollable ResultSet (JDBC 2.0).
  • Oracle 9i includes queryable snapshots of the main database which can offload the query to run against the clients local snapshot.
  • Performance should be considered at the start of a project
  • Given a simple SQL statement and a stored procedure call that accomplishes the same task, the simple SQL statement will always execute faster because the stored procedure executes the same SQL statement but also has the overhead of the procedure call itself. On the other hand complex tasks requiring several SQL statements can be faster using stored procedures as fewer network trips and data transfers will be needed.
  • Performance can be better if changes to the database are batched: turn off autocommit; add multiple SQL statements using the Statement.addBatch() method; execute Statement.executeBatch().
  • The ConnectionPoolDataSource (from JDBC3.0) and PooledConnection interfaces provide built-in support for connection pools.
  • Use Connection.setReadOnly(true) to optimize read-only database interactions.
  • Use Connection.nativeSQL() to see how the SQL query will execute in the database to help ensure that the SQL is optimized.
  • Use Connection.nativeSQL() to see how the SQL query will execute in the database to help ensure that the SQL is optimized.
  • Commit the data after the transaction completes rather than after each method call
  • Use the fastest driver available to the database: normally type 4 (preferably) or type 3.
  • Use the Page-by-Page Iterator pattern to repeatedly pass small amounts of data rather than huge chunks.
  • Reusing connections allows a prepared statement to be reused.
  • Database connection pools can take one of two strategies: a limited size pool, where attempts to make connections beyond the pool size must wait for a connection to become idle; or a flexible sized pool with a preferred size which removes idle connections as soon as the preferred size is exceeded (i.e. temporarily able to exceed the preferred size). The fixed size pool is generally considered to be the better choice.
  • Avoid the following common mistakes: Failure to close JDBC result sets, statements, and connections; Failure to remove unused stateful session beans; Failure to invalidate HttpSession.
  • CachedRowSet provides cached result sets that do not require continuous connection to the database, allowing connections to be reused more efficiently.
  • Reuse database connections using a connection pool.
  • Obtain and release pooled conections within each method that requires the resource if the connection is very short (termed “Quick Catch-and-Release Strategy” in the article). However do not release the connection only to use it again almost immediately, instead hold the connection until it will not be immediately needed.
  • Response time increasing too much when database is over populated probably indicates lack of or inappropriate indexing on the database.
  • Use SQL clause with EXPLAIN or similar (e.g. “Explain select * from table where tablefield = somevalue”) to ensure that the database is doing an indexed search rather than a linear searches of large datasets.

Web Page Performance : How To Improve it

  1. Make Fewer HTTP Requests
  2. Use a Content Delivery Network
  3. Add an Expires or a Cache-Control Header
  4. Gzip Components
  5. Put Stylesheets at the Top
  6. Put Scripts at the Bottom
  7. Avoid CSS Expressions
  8. Make JavaScript and CSS External
  9. Reduce DNS Lookups
  10. Minify JavaScript and CSS
  11. Avoid Redirects
  12. Remove Duplicate Scripts
  13. Configure ETags
  14. Make Ajax Cacheable
  15. Flush the Buffer Early
  16. Use GET for AJAX Requests
  17. Post-load Components
  18. Preload Components
  19. Reduce the Number of DOM Elements
  20. Split Components Across Domains
  21. Minimize the Number of iframes
  22. No 404s
  23. Reduce Cookie Size
  24. Use Cookie-free Domains for Components
  25. Minimize DOM Access
  26. Develop Smart Event Handlers
  27. Choose <link> over @import
  28. Avoid Filters
  29. Optimize Images
  30. Optimize CSS Sprites
  31. Don’t Scale Images in HTML
  32. Make favicon.ico Small and Cacheable
  33. Keep Components under 25K
  34. Pack Components into a Multipart Document

Refs:

http://developer.yahoo.com/performance/rules.html

http://developer.yahoo.com/performance/