The examples in this article summarize Java performance optimization techniques. Share it with everyone for your reference. The specific analysis is as follows:
Here we refer to some books and network resources, which are suitable for most Java applications.
In JAVA programs, most of the causes of performance problems do not lie in the JAVA language, but in the program itself. Developing good coding habits is very important and can significantly improve program performance.
1. Try to use the final modifier.
Classes with the final modifier are not derived. In the JAVA core API, there are many examples of applying final, such as java.lang.String. Specifying final for the String class prevents users from overriding the length() method. In addition, if a class is final, all methods of the class are final. The Java compiler will look for opportunities to inline all final methods (this depends on the specific compiler implementation). This can improve performance by an average of 50%.
2. Try to reuse objects.
Especially when using String objects, StringBuffer should be used instead when string concatenation occurs. Since the system not only has to spend 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.
3. Try to use local variables.
The parameters passed when calling the method and the temporary variables created during the call are saved in the stack (Stack), which is faster. Other variables, such as static variables, instance variables, etc., are created in the Heap and are slower.
4. Do not initialize variables repeatedly.
By default, when calling the constructor of a class, Java will initialize variables to certain values, all objects are set to null, integer variables are set to 0, float and double variables are set to 0.0, and logical values are set to false. This should be especially noted when a class is derived from another class, because when an object is created using the new keyword, all constructors in the constructor chain will be automatically called.
There is a note here. When setting the initial value for a member variable but need to call other methods, it is best to put it in a method such as initXXX(), because directly calling a method to assign a value may throw a null pointer exception because the class has not been initialized. public int state = this.getState();
5. In the development of Java+Oracle application systems, the SQL language embedded in Java should be in uppercase as much as possible to reduce the parsing burden of the Oracle parser.
6. During the Java programming process, perform database connections and I/O stream operations. After use, close them in time to release resources. Because operations on these large objects will cause a lot of system overhead.
7. Excessive creation of objects will consume a large amount of system memory, and in severe cases, may lead to memory leaks. Therefore, it is of great significance to ensure the timely recycling of expired objects.
The JVM's GC is not very smart, so it is recommended to manually set it to null after the object is used.
8. When using synchronization mechanism, try to use method synchronization instead of code block synchronization.
9. Minimize double counting of variables.
for example
for(int i=0;i<list.size();i++)
should be modified to
for(int i=0,len=list.size();i<len;i++)
10. Adopt a strategy of creating only when you need it.
For example:
String str="abc";if(i==1){ list.add(str);}
Should be modified to:
if(i==1){String str="abc"; list.add(str);}
11. Use exceptions with caution, as exceptions are detrimental to performance.
Throwing an exception first creates a new object. The constructor of the Throwable interface calls a local method named fillInStackTrace(). The fillInStackTrace() method checks the stack and collects call tracing information. Whenever an exception is thrown, the VM must adjust the call stack because a new object is created during processing.
Exceptions should only be used for error handling and should not be used to control program flow.
12. Do not use Try/Catch statements in loops. Try/Catch should be placed at the outermost level of the loop.
Error is a class for getting system errors, or virtual machine errors. Not all error exceptions can be obtained. If the virtual machine reports an error Exception, it cannot be obtained. You must use Error to obtain it.
13. Setting the initial capacity of StringBuffer through its constructor can significantly improve performance.
The default capacity of StringBuffer is 16. When the capacity of StringBuffer reaches the maximum capacity, it will increase its capacity to 2 times + 2 of the current capacity, which is 2*n+2. Whenever StringBuffer reaches her maximum capacity, she has to create a new array of objects and then copy the old array of objects, which wastes a lot of time. Therefore, it is necessary to set a reasonable initial capacity value for StringBuffer!
14. Use java.util.Vector reasonably.
Vector is similar to StringBuffer. Every time the capacity is expanded, all existing elements must be assigned to the new storage space. The default storage capacity of Vector is 10 elements, and the capacity is doubled.
vector.add(index,obj) This method can insert the element obj to the index position, but the index and subsequent elements must be moved downward by one position (increase their index by 1). Bad for performance unless necessary.
The same rules apply to the remove(int index) method, which removes the element at the specified position in this vector. Shift all subsequent elements left (decrement their index by 1). Returns the removed elements from this vector. Therefore, deleting the last element of the vector is much less expensive than deleting the first element. It is best to use the removeAllElements() method to remove all elements.
If you want to delete an element in the vector, you can use vector.remove(obj); you do not have to retrieve the element position yourself and then delete it, such as int index = indexOf(obj); vector.remove(index);
15. When copying large amounts of data, use System.arraycopy();
16. Code refactoring to increase code readability.
17. Create an instance of an object without using the new keyword.
When you create an instance of a class using the new keyword, all constructors in the constructor chain are automatically called. But if an object implements the Cloneable interface, we can call her clone() method. The clone() method does not call any class constructors.
The following is a typical implementation of the Factory pattern.
public static Credit getNewCredit(){ return new Credit();} The improved code uses the clone() method, private static Credit BaseCredit = new Credit(); public static Credit getNewCredit(){ return (Credit)BaseCredit.clone() ;}
18. If displacement can be used for multiplication and division, displacement should be used as much as possible, but it is best to add comments, because the displacement operation is not intuitive and difficult to understand.
19. Do not declare the array as: public static final.
20.HaspMap traversal.
Map<String, String[]> paraMap = new HashMap<String, String[]>();for( Entry<String, String[]> entry : paraMap.entrySet() ){ String appFieldDefId = entry.getKey(); String[] values = entry.getValue();}
Use the hash value to retrieve the corresponding Entry for comparison to obtain the result. After obtaining the entry value, directly obtain the key and value.
21. The use of array (array) and ArrayList.
Array array is the most efficient, but its capacity is fixed and cannot be changed dynamically. The capacity of ArrayList can be dynamically increased, but efficiency is sacrificed.
22. Single threads should try to use HashMap and ArrayList. Unless necessary, it is not recommended to use HashTable and Vector. They use a synchronization mechanism and reduce performance.
23. The difference between StringBuffer and StringBuilder is: java.lang.StringBuffer is a thread-safe variable character sequence. A string buffer similar to String, but cannot be modified. StringBuilder The StringBuilder class should generally be used in preference to this class because it supports all the same operations, but is faster because it does not perform synchronization. In order to obtain better performance, you should try to specify her capacity when constructing StringBuffer or StringBuilder. Of course, it is not necessary if it does not exceed 16 characters.
Under the same circumstances, using StringBuilder can only achieve a 10% to 15% performance improvement over using StringBuffer, but it will run the risk of multi-threading insecurity. After comprehensive consideration, it is recommended to use StringBuffer.
24. Try to use basic data types instead of objects.
25. Use simple numerical calculations instead of complex function calculations , such as looking up tables to solve trigonometric function problems.
26. Using concrete analogies is more efficient than using interfaces, but the structural flexibility is reduced, but modern IDEs can solve this problem.
27. Consider using static methods
If you don't need to access the outside of the object, make your method static. It will be called faster because it does not require a virtual function guide table. This colleague is also a good practice, because she tells you how to distinguish the nature of the method, calling this method will not change the state of the object.
28. The use of intrinsic GET and SET methods should be avoided as much as possible.
In Android programming, calling virtual methods will incur a lot of cost, which is more expensive than instance attribute query. We should only use get and set methods when outsourcing calls, but when calling internally, we should call them directly.
29. Avoid the use of enumerations and floating point numbers.
30. A two-dimensional array takes up more memory space than a one-dimensional array, about 10 times the calculation.
31. The SQLite database reads all the data of the entire table very quickly, but conditional queries take 30-50MS. When doing this, everyone should pay attention to using it as little as possible, especially nested searches!
I hope this article will be helpful to everyone’s Java programming.