Java Performance Tuning Tips

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.

 

7 thoughts on “Java Performance Tuning Tips

  1. Нанять детектива says:

    Онлайн-площадка — сайт лицензированного детективного агентства.
    Мы предлагаем поддержку в решении деликатных ситуаций.
    Группа опытных специалистов работает с предельной этичностью.
    Нам доверяют поиски людей и разные виды расследований.
    Заказать детектива
    Любой запрос рассматривается индивидуально.
    Применяем современные методы и ориентируемся на правовые стандарты.
    Нуждаетесь в ответственное агентство — вы нашли нужный сайт.

  2. www.clocksforlife.com says:

    This online store offers a large assortment of stylish timepieces for your interior.
    You can discover urban and timeless styles to match your home.
    Each piece is carefully selected for its design quality and accuracy.
    Whether you’re decorating a functional kitchen, there’s always a fitting clock waiting for you.
    best large picture frame wall clocks
    Our catalog is regularly refreshed with new arrivals.
    We ensure secure delivery, so your order is always in trusted service.
    Start your journey to better decor with just a few clicks.

  3. my-articles-online.com says:

    Этот портал дает возможность поиска работы по всей стране.
    На сайте размещены актуальные предложения от настоящих компаний.
    На платформе появляются варианты занятости в разнообразных нишах.
    Частичная занятость — выбор за вами.
    https://my-articles-online.com/
    Навигация интуитивно понятен и подходит на широкую аудиторию.
    Создание профиля очень простое.
    Нужна подработка? — начните прямо сейчас.

  4. casino games says:

    This website, you can find a wide selection of slot machines from famous studios.
    Users can experience classic slots as well as feature-packed games with stunning graphics and bonus rounds.
    If you’re just starting out or a casino enthusiast, there’s always a slot to match your mood.
    play aviator
    Each title are available anytime and designed for desktop computers and tablets alike.
    All games run in your browser, so you can get started without hassle.
    Platform layout is user-friendly, making it quick to find your favorite slot.
    Sign up today, and discover the world of online slots!

  5. money casino says:

    This website, you can find lots of online slots from leading developers.
    Users can experience classic slots as well as new-generation slots with vivid animation and exciting features.
    Whether you’re a beginner or a seasoned gamer, there’s something for everyone.
    slot casino
    The games are available anytime and optimized for desktop computers and smartphones alike.
    You don’t need to install anything, so you can get started without hassle.
    The interface is easy to use, making it simple to explore new games.
    Register now, and discover the excitement of spinning reels!

  6. Michaelnob says:

    Were you aware that 1 in 3 people taking prescriptions experience serious drug mistakes due to lack of knowledge?

    Your health requires constant attention. Every medication decision you make plays crucial role in your quality of life. Maintaining awareness about your prescriptions should be mandatory for successful recovery.
    Your health depends on more than following prescriptions. Every medication interacts with your biological systems in unique ways.

    Remember these life-saving facts:
    1. Combining medications can cause health emergencies
    2. Over-the-counter allergy medicines have potent side effects
    3. Altering dosages undermines therapy

    To protect yourself, always:
    ✓ Verify interactions via medical databases
    ✓ Review guidelines thoroughly when starting new prescriptions
    ✓ Ask your pharmacist about proper usage

    ___________________________________
    For professional medication guidance, visit:
    https://pbase.com/silagra/image/174947427

  7. DavidRox says:

    Our platform features buggy rentals throughout Crete.
    Visitors can safely reserve a machine for adventure.
    If you’re looking to explore mountain roads, a buggy is the exciting way to do it.
    https://linktr.ee/buggycrete
    Each buggy are safe and clean and offered with flexible bookings.
    Booking through this site is hassle-free and comes with clear terms.
    Start your journey and discover Crete like never before.

Leave a Reply

Your email address will not be published. Required fields are marked *