Optimize code and improve code performance

1. Method

1. Try to specify the final modifier of classes and methods

If a class is designated as final, all methods of the class are final. The Java compiler will look for opportunities to inline all final methods. Inlining plays a significant role in improving Java running efficiency. For details, see Java runtime optimization. This can improve performance by an average of 50%.

2. Variables

1. Do not continuously create object references within the loop

For example:

for (int i = 1; i <= count; i++){
    
    
	Object  obj = new Object;
}

This approach will cause count Object object references to exist in the memory. If the count is large, it will consume memory. It is recommended to change it to:

Object obj = null;
for (int i = 0; i <= count; i++) {
    
    
	obj = new Object; 
}

In this case, there is only one copy of the Object object reference in the memory. Every time a new Object is created, the Object object reference points to a different Object, but there is only one copy in the memory, which greatly saves memory space.

2. Convert basic types to strings

To convert a basic data type to a string, basic data type .toString is the fastest way, String.valueOf is the second, and data+"" is the slowest.

3. If the initial value of the variable will be overwritten, there is no need to assign an initial value to the variable.

Counterexample:

List<UserDO> userList = new ArrayList<>();
if (isAll) {
    
    
    userList = userDAO.queryAll();
} else {
    
    
    userList = userDAO.queryActive();
}

Positive example:

List<UserDO> userList;
if (isAll) {
    
    
    userList = userDAO.queryAll();
} else {
    
    
    userList = userDAO.queryActive();
}

4. Try to use basic data types and avoid unnecessary boxing, unboxing and null pointer judgment.

Counterexample:

public static double sum(Double value1, Double value2) {
    
    
    double double1 = Objects.isNull(value1) ? 0.0D : value1;
    double double2 = Objects.isNull(value2) ? 0.0D : value2;
    return double1 + double2;
}
double result = sum(1.0D, 2.0D);

Positive example:

public static double sum(double value1, double value2) {
    
    
    return value1 + value2;
}
double result = sum(1.0D, 2.0D);

3. Constants

1. Declare the constant as static final and name it in uppercase

In this way, these contents can be put into the constant pool during compilation to avoid calculating the value of the constant during runtime. In addition, naming constants in uppercase letters can also make it easier to distinguish constants from variables.

2. The use of JSON conversion objects is prohibited

Although there is no problem in function, there is a problem in performance.

4. Object

1. Reuse objects as much as possible

Especially for the use of String objects, StringBuilder/StringBuffer should be used instead when string connection occurs. Since the Java virtual machine not only spends time generating objects, it may also need to spend time garbage collecting and processing these objects in the future. Therefore, generating too many objects will have a great impact on the performance of the program.

5. Cycle

1. Don’t use try…catch… in a loop, put it in the outermost layer

Unless you have to. It is unreasonable to write this without any reason.

2. Selection of for, enhanced for, and iterator

Reference article: List traversal: for, foreach Iterator speed comparison
summary:iterator 性能更优

// 遍历Set
Set<String> set = new HashSet<>();
set.add("a");
set.add("a");
set.add("b");
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
    
    
    System.out.println(iterator.next());
}

// 遍历List
List<String> list = new ArrayList<>();
list.add("a");
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
    
    
    System.out.println(iterator.next());
}

// 遍历Map
Map<String, String> nameMap = new HashMap<>();
nameMap.put("student1", "lihua");
Set<Map.Entry<String, String>> entries = nameMap.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while(iterator.hasNext()){
    
    
	Map.Entry<String, String> entry = iterator.next();
	System.out.println(entry.getKey());
	System.out.println(entry.getValue());
}

6. Collection

1. ArrayList和LinkedList

ArrayList is used in scenarios where there are many sequential insertions and random accesses, and LinkedList is used in scenarios where there are many element deletions and intermediate insertions.

2. If you can estimate the length of the content to be added, try to specify the initial length.

For example, ArrayList, LinkedLlist, StringBuilder, StringBuffer, HashMap, HashSet, etc., taking StringBuilder as an example:

(1) StringBuilder//Allocates 16 characters of space by default

(2) StringBuilder(int size) // Allocate space of size characters by default

(3) StringBuilder(String str) // By default, 16 characters + str.length character space are allocated

(4) The default length of List is 10

(5) The default length of Map is 16

As soon as it reaches its maximum capacity, it has to create a new character array and then copy the contents of the old character array to the new character array - this is a very performance-consuming operation

7. String

1. Try to avoid using split

Unless it is necessary, you should avoid using split. Split supports regular expressions, so its efficiency is relatively low. Frequent calls of dozens or millions will consume a lot of resources. If you really need to call split frequently, you can Consider using apache's StringUtils.split(string,char). Frequent splits can cache the results.

2. Convert basic types to strings

To convert a basic data type to a string, basic data type .toString is the fastest way, String.valueOf is the second, and data+"" is the slowest.

3. When adding strings, use ' ' instead of " " if the string has only one character.

example:

public class STR {
    
    
	public void method(String s) {
    
    
		String string = s + "d" // violation.
		string = "abc" + "d" // violation.
	}
}

// 更正: 将一个字符的字符串替换成' '
public class STR {
    
    
	public void method(String s) {
    
    
		String string = s + "d // violation.
		string = "abc" + 'd' // violation.
	}
}

8. Method

1. Declare methods that have nothing to do with class member variables as static methods

The advantage of static methods is that they can be called directly without generating an instance of the class. Static methods no longer belong to an object, but to the class in which it is located. You only need to access it through its class name, and there is no need to consume resources to repeatedly create objects. Even private methods within a class should be declared as static methods if they do not use class member variables.

Counterexample:

public int getMonth(Date date) {
    
    
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.MONTH) + 1;
}

Positive example:

public static int getMonth(Date date) {
    
    
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.MONTH) + 1;
}

Guess you like

Origin blog.csdn.net/m0_46638350/article/details/132445880