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)
  • Asynchronous Logging Parameterized Messages (log4j2)
    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());
    }
  • Jasper Reports has a lazy loading at init() :
    JasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
            LocalJasperReportsContext localJasperReportsContext = new LocalJasperReportsContext(jasperReportsContext);
            localJasperReportsContext.setClassLoader(this.getClass().getClassLoader());
  • 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 pooling ?
  • Tune fetchSize when querying big number of rows from DB. (defualt is 10, which makes it slow) 
  • Mapper Objects: use MapStruct (fastest).

No comments :

My Blog List

Blog Archive

Disclaimer

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