30 Essential Java Code Optimization Techniques to Boost Performance
This article presents a comprehensive guide to Java code optimization, covering goals such as reducing code size and improving runtime efficiency, and detailing 30 practical techniques ranging from using final modifiers and reusing objects to efficient loop constructs, proper resource handling, and optimal collection usage.
Preface
Code optimization is an important topic. Some may think minor tweaks are useless, but many small improvements can cumulatively enhance performance, much like a whale feeding on many tiny shrimp.
If the project aims for quick, bug‑free delivery, large‑scale optimizations can be deferred; however, with sufficient time for development and maintenance, every detail matters.
Optimization Goals
Reduce code size
Improve code execution efficiency
Code Optimization Details
1. Use final for classes and methods
Marking classes as final prevents inheritance; many core Java classes (e.g., java.lang.String) are final. Final methods can be inlined by the compiler, significantly boosting performance—potentially up to 50%.
2. Reuse objects
Avoid creating unnecessary objects, especially String. Use StringBuilder or StringBuffer for concatenation to reduce object creation and garbage collection overhead.
3. Prefer local variables
Method parameters and temporary variables reside on the stack, which is faster than heap‑allocated static or instance variables. Stack variables are automatically reclaimed when the method exits.
4. Close streams promptly
Always close database connections and I/O streams after use to release resources and avoid heavy system overhead.
5. Avoid repeated calculations
Even a single‑line method call incurs overhead. Cache results when possible, e.g.: for (int i = 0; i < list.size(); i++) { ... } Replace with:
for (int i = 0, length = list.size(); i < length; i++) { ... }6. Apply lazy loading
Create objects only when needed:
if (i == 1) { String str = "aaa"; list.add(str); }7. Use exceptions sparingly
Throwing an exception creates a new object and captures a stack trace, which is costly. Exceptions should signal errors, not control flow.
8. Place try‑catch outside loops
Wrap the outermost block with try‑catch; avoid placing it inside frequently executed loops.
9. Pre‑size collections
When the expected size is known, initialize collections with an appropriate capacity (e.g., new StringBuilder(5000)) to avoid repeated resizing.
10. Use System.arraycopy for bulk copies
Leverage native array copy for better performance.
11. Replace multiplication/division with bit shifts
Bitwise operations are faster:
for (val = 0; val < 100000; val += 5) { a = val << 3; b = val >> 1; }Note: add comments for readability.
12. Avoid object creation inside loops
Creating objects each iteration increases memory usage; reuse a single reference when possible.
13. Prefer arrays over ArrayList when size is known
Arrays provide faster random access.
14. Prefer non‑synchronized collections
Use HashMap, ArrayList, StringBuilder unless thread safety is required; synchronized versions (e.g., Hashtable, Vector) incur overhead.
15. Do not declare arrays as public static final
Only the reference is constant; the array contents remain mutable and expose security risks.
16. Use singletons wisely
Singletons can reduce load time and resource usage when appropriate, such as for shared resources, controlled instance creation, or data sharing.
17. Limit static variables
Static references prevent garbage collection, leading to memory leaks.
18. Invalidate unused sessions
Call HttpSession.invalidate() to free session resources promptly.
19. Iterate RandomAccess collections with classic for loops
For ArrayList, a simple index loop is faster than foreach.
20. Prefer synchronized blocks over synchronized methods
Synchronize only the critical section to avoid unnecessary locking.
21. Declare constants as static final with uppercase names
This allows the compiler to place them in the constant pool.
22. Remove unused objects and imports
Eliminate dead code to reduce clutter and potential warnings.
23. Minimize reflection usage at runtime
Reflection is powerful but slow; cache reflective lookups or avoid them in performance‑critical paths.
24. Use connection pools and thread pools
Reusing connections and threads reduces the overhead of creation and destruction.
25. Use buffered I/O streams
BufferedReader, BufferedWriter, etc., significantly improve I/O efficiency.
26. Choose appropriate List implementation
Use ArrayList for random access and insertions; use LinkedList for frequent deletions and middle insertions.
27. Limit the number of method parameters
Too many parameters violate object‑oriented principles and increase error risk; consider encapsulating them in a DTO.
28. Write constant first in equals comparisons
Use "123".equals(str) to avoid NullPointerException.
29. Prefer i == 1 over 1 == i
Both are equivalent, but the former aligns with typical reading habits.
30. Avoid using toString on arrays
Array's toString() prints a hash code; use Arrays.toString() instead.
31. Beware of down‑casting large numeric types
Casting a long to int truncates high‑order bits, potentially yielding unexpected values.
32. Remove unused elements from shared collections
Failing to clean up can cause memory leaks.
33. Convert primitives to String efficiently
Prefer Integer.toString() (fastest), then String.valueOf(), and avoid concatenation with "" (slowest).
34. Iterate maps efficiently
Use entrySet() with an iterator for key‑value traversal; use keySet() if only keys are needed.
35. Close resources separately
Separate close() calls in try blocks to ensure each resource is released even if one throws an exception.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
