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.
<code>Map<String, String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// ...
}</code>Use Collection.isEmpty() to Check Emptiness
Prefer
collection.isEmpty()over
collection.size() == 0because the former is always O(1) while some
size()implementations may be O(n).
<code>if (collection.isEmpty()) {
// ...
}</code>Avoid Assigning Collection Implementations to Static Members Directly
Initialize static collections in a static block rather than using an anonymous initializer.
<code>private static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
}
</code>Specify Collection Initial Size
When possible, create collections with an expected capacity to reduce costly resizing.
<code>int[] arr = {1,2,3};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}</code>Use StringBuilder for Loop Concatenation
String concatenation inside loops should be replaced with
StringBuilderfor better performance.
<code>StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
String s = sb.toString();</code>RandomAccess for List Random Access
If a
Listsupports random access, check
instanceof RandomAccessbefore using index‑based operations.
<code>if (list instanceof RandomAccess) {
System.out.println(list.get(list.size() - 1));
} else {
// fallback for linked‑list implementation
}</code>Convert List to Set for Frequent contains Calls
Replace repeated
list.contains()(O(n)) with a
HashSet(O(1)).
<code>Set<Integer> set = new HashSet<>(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
set.contains(i);
}</code>Append Upper‑case L to Long Literals
Always use an upper‑case
Lfor long constants to avoid confusion with the digit
1.
<code>long value = 1L;
long max = Math.max(1L, 5L);
</code>Replace Magic Numbers with Named Constants
Define meaningful
static finalconstants instead of using raw numbers (except -1, 0, 1).
<code>private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++) {
// ...
}
</code>Delete Unused Private Methods, Fields, Local Variables, and Parameters
Removing dead code makes the codebase cleaner and easier to maintain.
<code>public int sum(int a, int b) {
return a + b;
}
</code>Remove Redundant Parentheses
Extra parentheses add visual noise; simplify expressions.
<code>return x;
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;
</code>Utility Classes Should Hide Their Constructor
Declare a private constructor to prevent instantiation.
<code>public class MathUtils {
public static final double PI = 3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) { return a + b; }
}
</code>Delete Redundant Exception Catch‑and‑Rethrow
If a catch block only rethrows the exception, remove it and let the method propagate the exception.
<code>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();
}
}
</code>Access Public Static Constants via Class Name
Reference static constants directly through the class, not an instance.
<code>String nameKey = User.CONST_NAME;
</code>Don’t Use NullPointerException for Null Checks
Check for null explicitly or use
Objects.isNull()instead of catching
NullPointerException.
<code>if (Objects.isNull(user)) {
return null;
}
return user.getName();
</code>Prefer String.valueOf() Over Concatenation with Empty String
Convert values to strings efficiently using
String.valueOf().
<code>int i = 1;
String s = String.valueOf(i);
</code>Mark Obsolete Code with @Deprecated
Annotate outdated methods with
@Deprecatedand provide replacement information.
<code>/**
* Save data.
* @deprecated Use {@link newSave()} instead.
*/
@Deprecated
public void save() { /* ... */ }
</code>Return Empty Arrays or Collections Instead of null
Methods should return empty results to avoid null checks.
<code>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();
}
</code>Prefer Constants in equals() Calls
Call
equals()on a known constant to avoid NPE, or use
Objects.equals().
<code>return OrderStatus.FINISHED.equals(status);
// or
return Objects.equals(status, OrderStatus.FINISHED);
</code>Enum Fields Should Be Private and Immutable
Declare enum attributes as
private finaland set them only via the constructor.
<code>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; }
}
</code>Be Careful with String.split() – It Uses Regex
Escape special regex characters when splitting.
<code>String[] parts = "a.ab.abc".split("\\."); // ["a","ab","abc"]
String[] parts2 = "a|ab|abc".split("\\|"); // ["a","ab","abc"]
</code>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.
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.