30 Essential Java Code Optimization Tips to Boost Performance
This article presents 30 practical Java code optimization techniques—from using final modifiers and reusing objects to lazy loading, efficient looping, proper resource handling, and optimal collection usage—explaining why each improves runtime speed, memory usage, and overall application performance.
Introduction
Code optimization is a very important topic. Some may think small tweaks are useless, but like a whale eating many tiny shrimp, the cumulative effect can fill the whale. Likewise, optimizing many tiny code details can significantly improve a program's efficiency.
Optimization Goals
Reduce code size
Improve runtime efficiency
Optimization Details
1. Prefer the final modifier for classes and methods
Marking a class as final prevents inheritance; marking a method as final prevents overriding. The JVM can inline final methods, which can raise performance by up to 50%.
2. Reuse objects
Especially for strings, use StringBuilder or StringBuffer instead of repeated concatenation to avoid unnecessary object creation and garbage collection.
3. Use local variables whenever possible
Method parameters and temporary variables stored on the stack are accessed faster than static or instance fields stored on the heap.
4. Close streams promptly
Always close database connections and I/O streams after use to release resources and avoid heavy overhead.
5. Avoid repeated calculations of the same variable
Cache results instead of calling methods repeatedly. Example: 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 they are needed. Example:
String str = "aaa";
if (i == 1) {
list.add(str);
}instead of creating the string before the condition.
7. Use exceptions sparingly
Throwing an exception creates a new object and captures a stack trace, which is costly. Use exceptions only for error handling, not for regular control flow.
8. Do not place try…catch inside loops
Wrap the entire loop in a single try‑catch block unless absolutely necessary; otherwise, an exception in one iteration can prevent cleanup of later resources.
9. Pre‑size collections when the size is known
For ArrayList, StringBuilder, etc., specify an initial capacity to avoid repeated resizing and copying.
10. Use System.arraycopy() for bulk copies
It is faster than element‑by‑element copying.
11. Replace multiplication/division with bit shifts
Bit‑shift operations are much faster. Example:
for (int val = 0; val < 100000; val += 5) {
a = val << 3; // val * 8
b = val >> 1; // val / 2
}12. Avoid creating objects inside loops
Instantiate objects outside the loop or reuse a single reference to reduce memory pressure.
13. Prefer arrays over ArrayList when size is fixed
Arrays have no overhead of dynamic resizing.
14. Prefer HashMap , ArrayList , StringBuilder over synchronized alternatives
Classes like Hashtable, Vector, StringBuffer incur synchronization costs.
15. Do not declare arrays as public static final
Such declarations give no real benefit and expose the array to external modification.
16. Use the Singleton pattern judiciously
Singletons can reduce load and resource usage but should only be applied where a single instance truly makes sense.
17. Avoid unnecessary static variables
Static references prevent garbage collection and can cause memory leaks.
18. Clear unused sessions
Invalidate HTTP sessions when they are no longer needed to free memory and avoid serialization overhead.
19. Iterate ArrayList with a classic for loop
For collections implementing RandomAccess, a simple index loop is faster than a foreach loop.
20. Prefer synchronized blocks over synchronized methods
Synchronize only the critical section to reduce contention.
21. Declare constants as static final with uppercase names
This places them in the constant pool and makes them easy to identify.
22. Remove unused objects and imports
Eliminate code that triggers warnings such as “variable is not used” or “import is never used”.
23. Avoid reflection in performance‑critical code
Reflection adds overhead; if needed, instantiate reflective classes once at startup.
24. Use connection pools and thread pools
Pooling reuses objects, reducing the cost of creating and destroying them.
25. Use buffered I/O streams
BufferedReader, BufferedWriter, etc., greatly improve I/O throughput.
26. Choose ArrayList for frequent random access and LinkedList for many insertions/removals
Understanding their internal mechanics guides the right choice.
27. Limit the number of parameters in public methods
Too many parameters hurt readability and increase the chance of errors; consider encapsulating them in an object.
28. Put constant string first in equals checks
Write "123".equals(str) to avoid possible NullPointerException.
29. Prefer if (i == 1) over if (1 == i) for readability
Both are equivalent in Java, but the former aligns with common coding style.
30. Do not use toString() on arrays
It yields an unreadable representation; use Arrays.toString() instead.
31. Avoid unsafe down‑casting of primitive types
Casting a large long to int truncates high‑order bits and can produce unexpected results.
32. Remove unused elements from shared collections
Failing to clean up can cause memory leaks in long‑lived collections.
33. Convert primitive types to strings efficiently
Use toString() (fastest), then String.valueOf(), and avoid concatenation with + "" (slowest).
34. Iterate Map efficiently
Iterate over entrySet() with an iterator for best performance; use keySet() if only keys are needed.
35. Close resources separately
Wrap each close() in its own try‑catch to ensure all resources are released even if one close 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.
ITFLY8 Architecture Home
ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.
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.
