15 Essential Java Backend Coding Practices to Boost Performance
This article presents fifteen practical Java backend coding guidelines—including avoiding "where 1=1" in MyBatis, iterating Map entrySet, using Collection.isEmpty, pre‑sizing collections, employing StringBuilder, preferring Set for contains checks, initializing static members correctly, removing dead code, shielding utility constructors, eliminating redundant catches, using String.valueOf, avoiding BigDecimal(double), returning empty collections, calling equals on constants, securing enum fields, and escaping regex in split—each illustrated with bad and good code examples to improve readability, safety, and efficiency.
1. MyBatis: Avoid using "where 1=1" for multiple conditions
Using "where 1=1" prevents the database from using indexes and may cause full table scans and SQL injection risks.
Incorrect 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>Correct 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>2. Iterate Map with entrySet() to get key and value efficiently
When both key and value are needed, iterating entrySet() is more performant than iterating keySet() and then calling get().
Incorrect example:
//Map get value bad example:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()) {
String value = map.get(key);
}Correct example:
//Map get key & value good example:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}3. Use Collection.isEmpty() to check emptiness
Calling Collection.isEmpty() is more readable and usually O(1), while size() may be O(n) for some implementations.
Incorrect example:
LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0) {
System.out.println("collection is empty.");
}Correct example:
LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()) {
System.out.println("collection is empty.");
}
// null check alternative
if (CollectionUtils.isEmpty(collection)) {
System.out.println("collection is null.");
}4. Specify collection size during initialization
Pre‑setting the initial capacity reduces the number of costly resize operations.
Incorrect example:
int[] arr = new int[]{1,2,3,4};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}Correct example:
int[] arr = new int[]{1,2,3,4};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}5. Use StringBuilder for string concatenation inside loops
In loops the compiler cannot optimise "+" concatenation, so StringBuilder should be used.
Incorrect example:
String str = "";
for (int i = 0; i < 10; i++) {
// concatenation not optimised
str += i;
}Correct example:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i);
}6. Use Set instead of List for frequent contains() checks
List.contains() is O(n); converting to a HashSet makes the check O(1).
Incorrect 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);
}
}Correct example:
List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>();
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 fields should be populated inside a static initializer rather than via an anonymous subclass.
Incorrect example:
private static Map<String, Integer> map = new HashMap<String, Integer>(){{
put("Leo",1);
put("Family-loving",2);
}};
private static List<String> list = new ArrayList<>(){{
add("Sagittarius");
}};Correct example:
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("Leo",1);
map.put("Family-loving",2);
}
private static List<String> list = new ArrayList<>();
static {
list.add("Sagittarius");
}8. Remove unused local variables, method parameters, private methods, fields and redundant parentheses
(Content omitted for brevity; the article advises cleaning dead code.)
9. Shield utility class constructors
Utility classes should have a private constructor to prevent instantiation.
Incorrect 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();
}
}Correct 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 catch blocks that only re‑throw
If a catch block does nothing but re‑throw, it can be omitted.
Incorrect 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;
}
}Correct 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. Convert objects to strings with String.valueOf()
String.valueOf(value) is more efficient than "" + value.
Incorrect example:
int num = 520;
String strLove = "" + num;Correct example:
int num = 520;
String strLove = String.valueOf(num);12. Avoid using BigDecimal(double)
BigDecimal(double) can introduce precision loss; use BigDecimal.valueOf(double) instead.
Incorrect example: BigDecimal bigDecimal = new BigDecimal(0.11D); Correct example:
BigDecimal bigDecimal = BigDecimal.valueOf(0.11D);13. Return empty arrays or collections instead of null
Returning empty collections prevents NullPointerExceptions and simplifies caller code.
Incorrect example:
public static Result[] getResults() { return null; }
public static List<Result> getResultList() { return null; }
public static Map<String, Result> getResultMap() { return null; }Correct 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 constants or known non‑null objects
Calling equals() on a constant avoids possible NullPointerExceptions.
Incorrect example: return fileName.equals("Charming"); Correct example:
return "Charming".equals(fileName);
// or Objects.equals("Charming", fileName)15. Enum fields should be private and immutable
Enum attributes must be private, final, and set only via the constructor; no setters.
Incorrect example:
public enum SwitchStatus {
DISABLED(0, "禁用"),
ENABLED(1, "启用");
public int value;
private String description;
public void setDescription(String description) { this.description = description; }
}Correct 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 split() treats its argument as a regular expression, characters like . and | must be escaped.
Incorrect example:
String[] split = "a.ab.abc".split(".");
String[] split1 = "a|ab|abc".split("|");Correct 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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
