Java Code Tuning - SGajre/Tutorial GitHub Wiki
Java Code tuning
- Don’t optimize before you know it’s necessary
- Use a profiler like PMD to find the real bottleneck
- Create a performance test suite for the whole application
- Work on the biggest bottleneck first
- Use StringBuilder to concatenate Strings programmatically and avoid +
- Use primitives where possible
- Try to avoid BigInteger and BigDecimal
- Check the current log level first
- Use Apache Commons libs like StringUtils.replace instead of String.replace
- Cache expensive resources, like database connections
- Use Stopwatch to check the execution time in the debug logs or The System.currentTimeMillis() method is the most basic measuring tool for tuning.
- Use Concurrent Collections to handle multithreaded application
- Use tools like JConsole,VisualVm to monitor Thread behavior like deadlock, livelock etc.
- Use AppDynamic, JConsole or VisualVM, JStat to analyze memory usage.
- Avoid using synchronization in read-only or single-threaded queries.
- Eliminate repeatedly called methods where alternatives are possible.
- Eliminate repeated casts by casting once and holding the cast item in a correctly typed variable.
- Iterator.hasNext() and Enumerator.hasMoreElements() do not need to be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead.
- Reuse objects, try not to create new object unless it is essential. And try to set null or weakrefernce so that it will be Garbage collected.
- Use System.arraycopy() to copy arrays.
- ArrayList is faster than Vector.
- Preset array capacity to as large as will be required.
- LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup.
- Program using interfaces so that the actual structure can be easily swapped to improve performance.
- Primitive data wrapper classes (e.g. Integer) are slower than using the primitive data directly.
- Null out references when they are no longer used so that garbage collection can reclaim their space.
- Use Soft References to recycle memory when required.
https://www.javaperformancetuning.com/tips/rawtips.shtml