Java Code Optimization Tips for Better Performance
This article presents a comprehensive collection of Java code optimization techniques—including using final modifiers, reusing objects, preferring local variables, proper resource handling, avoiding unnecessary object creation, and efficient looping—to reduce code size, improve execution speed, and enhance overall application performance.
Hello, I am a top-level architect.
Preface
Code optimization is an important topic. Some may think it is useless, but like a whale eating many tiny shrimp, the cumulative effect of many small optimizations can significantly improve performance.
If the project aims for quick, bug‑free release, you can focus on major issues and ignore fine details; however, with enough time for development and maintenance, every small optimization point adds up to noticeable efficiency gains.
The goals of code optimization are:
Reduce code size
Increase execution efficiency
Code Optimization Details
1. Prefer using the final modifier on classes and methods
Classes marked final cannot be subclassed (e.g., java.lang.String). Declaring a class or method as final allows the JVM to inline calls, which can improve runtime performance by up to 50%.
2. Reuse objects whenever possible
Especially for String handling, use StringBuilder / StringBuffer for concatenation to avoid creating many temporary objects and reduce garbage‑collection overhead.
3. Use local variables instead of fields when possible
Method parameters and temporary variables reside on the stack, which is faster than heap‑allocated static or instance fields.
4. Close streams promptly
Always close database connections and I/O streams after use to release resources and avoid memory leaks.
5. Avoid repeated calculations of the same expression
Cache results such as list.size() before a loop:
for (int i = 0, length = list.size(); i < length; i++) {
...
}6. Apply lazy loading
Instantiate objects only when needed, e.g., create a String inside the conditional block rather than before it.
7. Use exceptions sparingly
Throwing an exception creates a Throwable and captures a stack trace, which is costly; use exceptions only for error handling, not for flow control.
8. Place try…catch outside loops
Wrapping the whole loop in a single try…catch can cause performance penalties and makes the code harder to read.
9. Pre‑size collections when the expected size is known
For example, initialize ArrayList with an appropriate capacity to avoid repeated resizing:
ArrayList(int size) // allocates space for 'size' elements10. Use System.arraycopy() for bulk copying
11. Replace multiplication/division with bit shifts when possible
Example:
for (val = 0; val < 100000; val += 5) {
a = val << 3; // val * 8
b = val >> 1; // val / 2
}12. Avoid creating objects inside tight loops
Reuse a single reference instead of allocating a new object each iteration.
13. Prefer arrays over ArrayList when random access is frequent
14. Prefer HashMap , ArrayList , StringBuilder over synchronized alternatives unless thread safety is required
15. Do not declare arrays as public static final
Such declarations expose mutable state and can become a security risk.
16. Use the Singleton pattern judiciously
Singletons help control resource usage, instance creation, and data sharing, but should only be applied where appropriate.
17. Minimize use of static variables
Static references are not reclaimed by the GC until the class is unloaded, potentially causing memory leaks.
18. Invalidate unused HTTP sessions promptly
Calling HttpSession.invalidate() frees session resources and prevents memory pressure.
19. Iterate RandomAccess collections with a classic for loop rather than foreach
This yields better performance for random‑access structures like ArrayList.
20. Prefer synchronized blocks over synchronized methods
Synchronize only the critical section to reduce contention.
21. Declare constants as static final and use uppercase naming
This allows the compiler to place them in the constant pool.
22. Remove unused imports and variables
Clean code improves readability and eliminates unnecessary bytecode.
23. Avoid reflection in performance‑critical paths
Reflection incurs overhead; if needed, cache reflective objects at startup.
24. Use connection pools and thread pools
Pooling reduces the cost of repeatedly opening connections and creating threads.
25. Use buffered I/O streams
BufferedReader, BufferedWriter, BufferedInputStream, and BufferedOutputStream dramatically improve I/O throughput.
26. Choose ArrayList for frequent random access and LinkedList for many insertions/removals
27. Limit the number of parameters in public methods
Three to four parameters are a reasonable upper bound; encapsulate data in objects when more are needed.
28. Write constant strings first in equals checks to avoid NPEs
Use "123".equals(str) instead of str.equals("123").
29. Prefer i == 1 over 1 == i for readability in Java
30. Do not use toString() on arrays; it yields unreadable output
31. Beware of data loss when casting large numbers to smaller types
Casting long to int truncates high‑order bits.
32. Remove unused elements from shared collections promptly
Failing to do so can cause memory leaks.
33. Convert primitive types to strings efficiently
Prefer Integer.toString() over String.valueOf() and avoid concatenation with + "" for best performance.
34. Iterate Map efficiently using entrySet iterator
HashMap<String, String> map = new HashMap<>();
map.put("111", "222");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
Iterator<Map.Entry<String, String>> iter = entrySet.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}35. Close resources in separate try‑catch blocks
Ensures each close() is attempted even if a previous one throws an exception.
These practices collectively help developers write more efficient, maintainable, and robust Java applications.
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.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.
