Boost Java Performance: 20 Essential Code Smell Fixes and Best Practices
This article compiles practical Java performance tips—from iterating Map.entrySet() and using Collection.isEmpty() to avoiding magic numbers, hiding utility class constructors, preferring StringBuilder, returning empty collections, and handling enums—helping developers write cleaner, faster, and more maintainable backend code.
Let Code Perform Better
When you need both keys and values from a Map, iterate entrySet() instead of keySet() followed by get() for higher efficiency.
Map<String, String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}Use Collection.isEmpty() to Check Emptiness
Prefer collection.isEmpty() over collection.size() == 0 because the former is always O(1) while some size() implementations may be O(n).
if (collection.isEmpty()) {
// ...
}Avoid Assigning Collection Implementations to Static Members Directly
Initialize static collections in a static block rather than using an anonymous initializer.
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
}Specify Collection Initial Size
When possible, create collections with an expected capacity to reduce costly resizing.
int[] arr = {1,2,3};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}Use StringBuilder for Loop Concatenation
String concatenation inside loops should be replaced with StringBuilder for better performance.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
String s = sb.toString();RandomAccess for List Random Access
If a List supports random access, check instanceof RandomAccess before using index‑based operations.
if (list instanceof RandomAccess) {
System.out.println(list.get(list.size() - 1));
} else {
// fallback for linked‑list implementation
}Convert List to Set for Frequent contains Calls
Replace repeated list.contains() (O(n)) with a HashSet (O(1)).
Set<Integer> set = new HashSet<>(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
set.contains(i);
}Append Upper‑case L to Long Literals
Always use an upper‑case L for long constants to avoid confusion with the digit 1.
long value = 1L;
long max = Math.max(1L, 5L);Replace Magic Numbers with Named Constants
Define meaningful static final constants instead of using raw numbers (except -1, 0, 1).
private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++) {
// ...
}Delete Unused Private Methods, Fields, Local Variables, and Parameters
Removing dead code makes the codebase cleaner and easier to maintain.
public int sum(int a, int b) {
return a + b;
}Remove Redundant Parentheses
Extra parentheses add visual noise; simplify expressions.
return x;
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;Utility Classes Should Hide Their Constructor
Declare a private constructor to prevent instantiation.
public class MathUtils {
public static final double PI = 3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) { return a + b; }
}Delete Redundant Exception Catch‑and‑Rethrow
If a catch block only rethrows the exception, remove it and let the method propagate the exception.
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}Access Public Static Constants via Class Name
Reference static constants directly through the class, not an instance.
String nameKey = User.CONST_NAME;Don’t Use NullPointerException for Null Checks
Check for null explicitly or use Objects.isNull() instead of catching NullPointerException.
if (Objects.isNull(user)) {
return null;
}
return user.getName();Prefer String.valueOf() Over Concatenation with Empty String
Convert values to strings efficiently using String.valueOf().
int i = 1;
String s = String.valueOf(i);Mark Obsolete Code with @Deprecated
Annotate outdated methods with @Deprecated and provide replacement information.
/**
* Save data.
* @deprecated Use {@link newSave()} instead.
*/
@Deprecated
public void save() { /* ... */ }Return Empty Arrays or Collections Instead of null
Methods should return empty results to avoid null checks.
public static Result[] getResults() {
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}Prefer Constants in equals() Calls
Call equals() on a known constant to avoid NPE, or use Objects.equals().
return OrderStatus.FINISHED.equals(status);
// or
return Objects.equals(status, OrderStatus.FINISHED);Enum Fields Should Be Private and Immutable
Declare enum attributes as private final and set them only via the constructor.
public enum UserStatus {
DISABLED(0, "禁用"),
ENABLED(1, "启用");
private final int value;
private final String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public int getValue() { return value; }
public String getDescription() { return description; }
}Be Careful with String.split() – It Uses Regex
Escape special regex characters when splitting.
String[] parts = "a.ab.abc".split("\\."); // ["a","ab","abc"]
String[] parts2 = "a|ab|abc".split("\\|"); // ["a","ab","abc"]Summary
This article, written by Java senior engineer Wang Chao, gathers practical Java development experience, offering dozens of tips to avoid common pitfalls and write more efficient, elegant code.
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.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.
