30 November 2017

Java Performance

This is a summary post of good practices (many easy) to improve performance in your Java code:
  •  use Apache commons-lang StringUtils.replace() instead String.replace(). The big difference is because Java replace() uses regexp which makes it more expensive immediately.
  • avoid regexp if possible (many times we use regexp and with a String.indexof() is enough).  also, Apache commons lang: StringUtils.replace("hola\nmundo\n", "\n", "");
  • avoid using Java7 UUID (there are other faster libraries for it) (randomness trends to be slow).
    https://github.com/jchambers/fast-uuid    (* this looks interesting)
  • Asynchronous Logging Parameterized Messages (log4j2) (Ring buffer - LMAX Disruptor)
    Many logging libraries offer an API for logging parameterized messages. This enables application code to look something like this:
    logger.debug("Entry number: {} is {}", i, entry[i]);
    without API:
    if (logger.isDebugEnabled()) {
        logger.debug("Entry number: " + i + " is " + entry[i].toString());
    The best solution is placeholders and if{}
    if (logger.isDebugEnabled()) {
        logger.debug("Entry number: {} is {}", i, entry[i]);
    lambda java8:
    logger.trace("Some long-running operation returned {}", () -> expensiveOperation());
  • Jasper Reports has a lazy loading at init() :
    JasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
            LocalJasperReportsContext localJasperReportsContext = new LocalJasperReportsContext(jasperReportsContext);
  • StringBuilder or StringBuffer over String (for concatenation)
  • Primitive over wrapper, such us, Integer, Double etc, ie:
    The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
  • Sorted of sorted List Java sorted ??? (Big Theta!)
  • String concatenating one line, it's not a problem
  • BigInteger BigDecimal are expensive. (avoid)
  • Cache database connections. Object pooling. Apache common pool, Fast Object Pool, Vibur Object Pool
  • Tune fetchSize when querying big number of rows from DB. (default is 10, which makes it slow) 
  • Mapper Objects: use MapStruct (fastest).
  • log4j contention when writing to log file (asyng, buffer, network as solution)
  • exceptions are "expensives"
  • Timeouts!
    Socket_timeouts TCP_NODELAY, SO_SNDBUF, SO_RCVBUF, HTTP, JAX-WS, RestTemplate, JDBC timeouts :P
  • Thread synchronized (as seen on log4j), blocking java monitor

No comments :

My Blog List

Blog Archive


The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.