JAVA optimization interview points

1. MyBatis do not write 1 = 1 for multiple query criteria

When multiple query conditions are encountered, using where 1=1 can easily solve our problem, but it may cause very large performance loss. Because after adding the "where 1=1" filter condition, the database system cannot use query optimization strategies such as index, and the database system will be forced to scan each row of data (i.e. full table scanning) To compare whether this row meets the filtering conditions. When the amount of data in the table is large, the query speed will be very slow; In addition, there is a risk of SQL injection.

<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 entrySet() to get the key and value of the Map

When only the primary key of the Map needs to be obtained in the loop, the iterative keySet() is correct; However, when the primary key key and value are required, it is more efficient to iterate entrySet(), which has better performance than iterating keySet() first and then get ting value.

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 detect null

There is no logical problem using Collection.size() to detect whether it is empty, but using Collection.isEmpty() makes the code easier to read and better performance; In addition, the time complexity of any Collection.isEmpty() implementation is O(1), which does not require multiple loop traversal, but the time complexity of some implementations through the Collection.size() method may be O(n). Example of O(1) latitude reduction cycle times

LinkedList<Object> collection = new LinkedList<>();
  if (collection.isEmpty()){
      System.out.println("collection is empty.");
  }

  //To detect whether it is null, CollectionUtils.isEmpty() can be used
  if (CollectionUtils.isEmpty(collection)){
      System.out.println("collection is null.");
  }

4. When initializing a collection, try to specify its size

Specifying the size of the set during initialization can effectively reduce the number of expansion of the set, because the time complexity of each expansion of the set is likely to be O(n), which consumes time and performance.

//Initialize the list and add elements to the list. Positive example:
  int[] arr = new int[]{1,2,3,4};
  //Specifies the capacity size of the collection list
  List<Integer> list = new ArrayList<>(arr.length);
  for (int i : arr){
      list.add(i);
  }

5. Splicing strings using StringBuilder

Generally, string splicing will be optimized by Java at compile time, but string splicing in the loop cannot be optimized at compile time, so it needs to be replaced by StringBuilder.

Counterexample:

//Concatenate string Counterexamples in loops
String str = "";
for (int i = 0; i < 10; i++){
  //String splicing in a loop is not optimized by Java
  str += i;
}

Positive example:

//Splicing positive examples of strings in a loop
 String str1 = "Love";
 String str2 = "Courage";
 String strConcat = str1 + str2;  //The Java compiler optimizes string splicing in this normal mode
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < 10; i++){
     //In the loop, the Java compiler cannot optimize, so use StringBuilder manually
      sb.append(i);
  }

6. If the Collection.contains method needs to be called frequently, use Set

In the Java collection class library, the general time complexity of the contains method of list is O(n). If the contains method needs to be called frequently in the code to find data, first convert the collection list into a HashSet implementation, and the time complexity of O(n) will be O(1).

  Set<Object> set = new HashSet<>();
  for (int i = 0; i <= Integer.MAX_VALUE; i++){
      //The time complexity is O(1)
      if (set.contains(i)){
          System.out.println("list contains "+ i);
      }
  }

7. Using static code blocks to assign static member variables

For static member variables of collection type, static code block assignment should be used instead of collection implementation.

private static Map<String, Integer> map = new HashMap<String, Integer>();
    static {
        map.put("Leo",1);
        map.put("Family-loving",2);
        map.put("Cold on the out side passionate on the inside",3);
    }

private static List<String> list = new ArrayList<>();
    static {
        list.add("Sagittarius");
        list.add("Charming");
        list.add("Perfectionist");
    }

8. Avoid using BigDecimal(double)

BigDecimal(double) has the risk of accuracy loss, which may lead to business logic exceptions in the scenario of accurate calculation or value comparison.

BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

9. Returns empty arrays and collections instead of null

If the program returns null, the caller needs to force null detection, otherwise a null pointer exception will be thrown; Returning an empty array or empty collection effectively avoids the caller throwing a null pointer exception because it does not detect null. It can also delete the caller's null detection statement to make the code more concise.

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();
}

10. The equals method is called preferentially with constants or fixed values

The equals method of an object is easy to throw null pointer exceptions. You should call the equals method with a constant or an object with a certain value.

private static boolean fileReader(String fileName)throws IOException{
	// The equals method is called using a constant or an object that is determined to have a value
	return "Charming".equals(fileName);

	//Or use the: java.util.Objects.equals() method
	return Objects.equals("Charming",fileName);
}

11. The property fields of an enumeration must be private and immutable

Enumerations are usually used as constants. If there are public attribute fields or setting field methods in enumerations, the attributes of these enumerating constants can be easily modified; Ideally, the attribute field in the enumeration is private and assigned in the private constructor. There is no corresponding Setter method. It is best to add the final modifier.

public enum SwitchStatus {
//Enumerated property field positive example
DISABLED(0, "disabled"),
ENABLED(1, "enabled");

// final modification
private final int value;
private final String description;

private SwitchStatus(int value, String description) {
    this.value = value;
    this.description = description;
}

// There is no Setter method
public int getValue() {
    return value;
}

public String getDescription() {
    return description;
}
}

12. Some keywords of string.split (string regex) need to be translated

When using the split method of String, if the incoming delimited String is a regular expression, some keywords (such as |Etc.) need escape.

// Translation required
String[] split2 = "a.ab.abc".split("\\.");
System.out.println(Arrays.toString(split2));  // The result is ["a", "ab", "abc"]

// |Translation required
String[] split3 = "a|ab|abc".split("\\|");
System.out.println(Arrays.toString(split3));  // The result is ["a", "ab", "abc"]

Tags: Java Interview Back-end

Posted by jtacon on Fri, 15 Oct 2021 06:19:02 +0530