Boost Java Performance: 16 Proven Coding Practices You Should Adopt
This article presents sixteen practical Java coding guidelines—ranging from avoiding "where 1=1" in MyBatis to using static blocks for collection initialization, preferring Set over List for contains checks, and returning empty collections instead of null—to help developers write more efficient, readable, and safe backend code.
1. MyBatis – Do Not Use "where 1=1" for Multiple Conditions
Using where 1=1 may simplify query building but prevents the database from using indexes, leading to full table scans and severe performance loss, especially on large tables, and also introduces SQL‑injection risks.
Bad example:
<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
select count(*) from t_rule_BookInfo t where 1=1
<if test="title !=null and title !=''">
AND title = #{title}
</if>
<if test="author !=null and author !=''">
AND author = #{author}
</if>
</select>Good example:
<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
select count(*) from t_rule_BookInfo t
<where>
<if test="title !=null and title !=''">
title = #{title}
</if>
<if test="author !=null and author !=''">
AND author = #{author}
</if>
</where>
</select>The same principle applies to UPDATE statements—use <where> instead of a dummy 1=1 condition.
2. Iterate entrySet() to Get Map Keys and Values
When both key and value are needed, iterating entrySet() is more efficient than iterating keySet() and calling get() for each key.
Bad example:
for (String key : map.keySet()) {
String value = map.get(key);
}Good example:
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}3. Use Collection.isEmpty() to Test Emptiness
Calling isEmpty() is more readable and usually O(1), while size()==0 may require O(n) traversal for some collections.
Bad example:
if (collection.size() == 0) {
System.out.println("collection is empty.");
}Good example:
if (collection.isEmpty()) {
System.out.println("collection is empty.");
}
// For null‑safe check you can use CollectionUtils.isEmpty(collection)
if (CollectionUtils.isEmpty(collection)) {
System.out.println("collection is null.");
}4. Specify Collection Size When Initializing
Providing an initial capacity reduces the number of internal array expansions, each of which can be O(n) and costly.
Bad example:
int[] arr = {1,2,3,4};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}Good example:
int[] arr = {1,2,3,4};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}5. Use StringBuilder for String Concatenation in Loops
In a loop the compiler cannot optimise the '+' operator, so StringBuilder should be used to avoid creating many intermediate String objects.
Bad example:
String str = "";
for (int i = 0; i < 10; i++) {
str += i;
}Good example:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}
String result = sb.toString();6. Use Set When contains() Is Called Frequently
List.contains() is O(n); converting the list to a HashSet makes the lookup O(1).
Bad example:
List<Object> list = new ArrayList<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
if (list.contains(i)) {
System.out.println("list contains " + i);
}
}Good example:
List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
if (set.contains(i)) {
System.out.println("list contains " + i);
}
}7. Initialise Static Collection Members in a Static Block
Static collections should be populated inside a static initializer rather than using an anonymous inner class.
Bad example:
private static Map<String, Integer> map = new HashMap<String, Integer>(){{
put("Leo",1);
put("Family-loving",2);
put("Cold on the outside passionate on the inside",3);
}};
private static List<String> list = new ArrayList<String>(){{
add("Sagittarius");
add("Charming");
add("Perfectionist");
}};Good example:
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("Leo",1);
map.put("Family-loving",2);
map.put("Cold on the outside passionate on the inside",3);
}
private static List<String> list = new ArrayList<>();
static {
list.add("Sagittarius");
list.add("Charming");
list.add("Perfectionist");
}8. Delete Unused Local Variables, Method Parameters, Private Methods, Fields and Redundant Parentheses
Removing dead code and unnecessary parentheses reduces clutter and improves compilation speed.
9. Shield Constructor in Utility Classes
Utility classes should not be instantiated; declare a private constructor to hide the implicit public one.
Bad example:
public class PasswordUtils {
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
}Good example:
public class PasswordUtils {
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
private PasswordUtils() {}
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
}10. Remove Redundant Exception Catching and Re‑throw
If a catch block only re‑throws the exception, it can be omitted.
Bad example:
private static String fileReader(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Exception e) {
throw e; // redundant
}
}Good example:
private static String fileReader(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}11. Use String.valueOf(value) Instead of "" + value
String.valueOf() is more efficient than concatenating with an empty string.
Bad example:
int num = 520;
String strLove = "" + num;Good example:
int num = 520;
String strLove = String.valueOf(num);12. Avoid Using BigDecimal(double)
Constructing a BigDecimal from a double can introduce precision loss; use BigDecimal.valueOf(double) instead.
Bad example: BigDecimal bigDecimal = new BigDecimal(0.11D); Good example:
BigDecimal bigDecimal = BigDecimal.valueOf(0.11D);13. Return Empty Arrays or Collections Instead of null
Returning empty structures prevents NullPointerException and eliminates the need for null checks by callers.
Bad example:
public static Result[] getResults() { return null; }
public static List<Result> getResultList() { return null; }
public static Map<String, Result> getResultMap() { return null; }Good example:
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(); }14. Call equals() on a Constant or Known Non‑null Value
Calling constant.equals(variable) avoids possible NullPointerException .
Bad example: return fileName.equals("Charming"); Good example:
return "Charming".equals(fileName);
// or Objects.equals("Charming", fileName);15. Enum Fields Must Be Private and Immutable
Enum attributes should be private final and set only in the constructor; no setters should be provided.
Bad example:
public enum SwitchStatus {
DISABLED(0, "禁用"),
ENABLED(1, "启用");
public int value;
private String description;
private SwitchStatus(int value, String description) { this.value = value; this.description = description; }
public void setDescription(String description) { this.description = description; }
}Good example:
public enum SwitchStatus {
DISABLED(0, "禁用"),
ENABLED(1, "启用");
private final int value;
private final String description;
private SwitchStatus(int value, String description) { this.value = value; this.description = description; }
public int getValue() { return value; }
public String getDescription() { return description; }
}16. Escape Special Characters When Using String.split(String regex)
Since the argument of split is a regular expression, characters like . or | must be escaped.
Bad example:
String[] split = "a.ab.abc".split(".");
String[] split1 = "a|ab|abc".split("|");Good example:
String[] split2 = "a.ab.abc".split("\\.");
String[] split3 = "a|ab|abc".split("\\|");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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
