Java code optimization details
Code optimization details @ h_ 301_ 2@
1. Try to specify the final modifier @ h of classes and methods_ 301_ 2 @ classes with the final modifier are not derivable. In the Java core API, there are many examples of applying final, such as Java Lang. string, the whole class is final. Specifying a final modifier for a class prevents the class from being inherited, and specifying a final modifier for a method prevents the method from being overridden. If a class is specified as final, all methods of that class are final. The java compiler will look for opportunities to inline all final methods, which plays an important role in improving the efficiency of Java operation_ 301_ 2@
2. Reuse object @ h as much as possible_ 301_ 2@ especially for the use of string objects, StringBuilder / StringBuffer should be used instead of string connection. Because the Java virtual machine not only takes time to generate objects, but also takes time to garbage collect and process these objects in the future, generating too many objects will have a great impact on the performance of the program@ H_ 301_ 2@
3. Use the local variable @ h whenever possible_ 301_ 2@ the parameters passed when calling the method and the temporary variables created in the call are saved in the stack, which is faster. Other variables, such as static variables and instance variables, are created in the heap, which is slower. In addition, the variables created in the stack will disappear as the method runs, and no additional garbage collection is required@ H_ 301_ 2@
4. Close flow @ h in time_ 301_ 2 @ in the process of Java programming, be careful in database connection and I / O flow operation. After use, close it in time to release resources. Because the operation of these large objects will cause large system overhead, a little carelessness will lead to serious consequences@ H_ 301_ 2@
5. Minimize repeated calculation of variables @ h_ 301_ 2@ clarify a concept that even if there is only one sentence in the method, it will consume, including creating stack frame, protecting the site when calling the method, restoring the site when calling the method, etc. So, for example, the following operations:
for(inti = 0; i < list.size(); i++)@H_ 301_ 2@ {...} It is suggested to replace with:
for(inti = 0,length = list.size(); i < length; i++)@H_ 301_ 2@ {...} @ H_ 301_ 2 @ so, on the list When size () is very large, it reduces a lot of consumption @ H_ 301_ 2@
6. Try to use the lazy loading strategy, that is, create @ h when necessary_ 301_ 2@
7. Use with caution exception @ h_ 301_ 2 @ abnormality is bad for performance. To throw an exception, first create a new object. The constructor of the throwable interface calls the local synchronization method named fillinstacktrace(). The fillinstacktrace() method checks the stack and collects call trace information. Whenever an exception is thrown, the Java virtual machine must adjust the call stack because a new object is created during processing. Exceptions can only be used for error handling and should not be used to control program flow@ H_ 301_ 2@
8. Don't use try... Catch... In a loop. Put it on the outermost layer
According to the opinions put forward by netizens, this point is worth discussing @ H_ 301_ 2@
9. If the length of the content to be added can be estimated, specify the initial length @ h for the underlying collection and tool class implemented in array_ 301_ 2 @ for example, ArrayList, linkedllist, StringBuilder, StringBuffer, HashMap, HashSet, etc. take StringBuilder as an example: @ h_ 301_ 2 @ (1) stringbuilder() / / 16 character space @ h is allocated by default_ 301_ 2 @ (2) StringBuilder (int size) / / a space of size characters @ h is allocated by default_ 301_ 2 @ (3) StringBuilder (string STR) / / 16 characters + str.length () character space @ h is allocated by default_ 301_ 2 @ you can use class (this refers not only to the StringBuilder above) constructor to set its initialization capacity, which can significantly improve the performance. For example, StringBuilder, length indicates the number of characters that the current StringBuilder can maintain. Because when the StringBuilder reaches the maximum capacity, it will increase its capacity to twice the current capacity and then add 2, whenever it only needs stri When ngbuilder 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. Imagine that if it can be estimated that 5000 characters will be stored in the character array without specifying the length, the nearest power of 5000 is 4096, and 2 is added for each expansion, then: @ h_ 301_ 2 @ (1) on the basis of 4096, apply for 8194 character arrays, which is equivalent to applying for 12290 character arrays at one time. If 5000 character arrays can be specified at the beginning, more than double the space @ h_301_2 will be saved@ (2) Copy the original 4096 characters to the new character array @ h_301_2 @ this will not only waste memory space but also reduce the code running efficiency. Therefore, it is not wrong to set a reasonable initialization capacity for the underlying set and tool class implemented by array, which will bring immediate effect. However, note that HashMap is a set implemented by array + linked list All right, don't set the initial size the same as your estimated size, because the possibility of connecting only one object to a table is almost zero. The initial size is recommended to be set to the nth power of 2. If it can be estimated that there are 2000 elements, it can be set to new HashMap (128) and new HashMap (256)@ H_ 301_ 2@
10. When copying large amounts of data, use system Arraycopy() command @ h_ 301_ 2@
11. Multiplication and division use shift operation @ H_ 301_ 2@
12. Don't keep creating object references @ h in the loop_ 301_ 2@
For example:
This will cause count object references in memory. If the count is large, memory will be consumed. It is recommended to change to:
In this way, there is only one object object reference in memory. Each time a new object() is created, the object object reference points to a different object, but there is only one in memory, which greatly saves memory space@ H_ 301_ 2@
13. In consideration of efficiency and type checking, array should be used as much as possible, and only when the array size cannot be determined ArrayList@H_301_2 @
14. Try to use HashMap, ArrayList and StringBuilder. Unless required by thread safety, hashtable, vector and StringBuffer are not recommended. The latter three cause performance overhead @ h due to the use of synchronization mechanism_ 301_ 2@
15. Do not declare the array as public static final @ H_ 301_ 2@
Because this is meaningless, it only defines the reference as static final, and the contents of the array can be changed at will. Declaring the array as public is a security vulnerability, which means that the array can be changed by external classes @ H_ 301_ 2@
16. Try to use single case @ h in appropriate occasions_ 301_ 2 @ using singleton can reduce the load, shorten the loading time and improve the loading efficiency, but it is not applicable to singleton everywhere. In short, singleton is mainly applicable to the following three aspects: @ h_ 301_ 2 @ (1) control the use of resources and control the concurrent access of resources through thread synchronization @ h_301_2 @ (2) control the generation of instances to save resources @ h_301_2 @ (3) control the sharing of data and enable communication between multiple unrelated processes or threads without establishing direct association
17. Try to avoid using static variables arbitrarily
At this time, the life cycle of static variable B is the same as that of class A. if class A is not unloaded, the B object pointed to by reference B will reside in memory until the program terminates @ H_ 301_ 2@
18. Clear unnecessary sessions in time @ h_ 301_ 2 @ in order to clear inactive sessions, many application servers have a default session timeout of 30 minutes. When the application server needs to save more sessions, if the memory is insufficient, the operating system will transfer some data to disk, The application server may also be based on the MRU (most frequently used recently) the algorithm dumps some inactive sessions to disk, and may even throw an exception of insufficient memory. If a session is to be dumped to disk, it must be serialized first. In large-scale clusters, the cost of serializing objects is very expensive. Therefore, when the session is no longer needed, the invalidate() of httpsession should be called in time Method to clear the session@ H_ 301_ 2@
19. Collections that implement the randomaccess interface, such as ArrayList, should use the most common for loop instead of the foreach loop to traverse @ H_ 301_ 2 @ this is recommended by JDK to users. The JDK API explains the randomaccess interface as follows: the randomaccess interface is implemented to show that it supports fast random access. The main purpose of this interface is to allow general algorithms to change their behavior, so that it can provide good performance when applied to random or continuous access lists. Practical experience shows that if the class instance implementing randomaccess interface is accessed randomly, the efficiency of using ordinary for loop will be higher than that of using foreach loop; Conversely, if it is accessed sequentially, it is more efficient to use iterator. A code similar to the following can be used for judgment:
The underlying implementation principle of foreach loop is iterator, so the latter half sentence "conversely, if it is accessed sequentially, it will be more efficient to use iterator" means that those class instances accessed sequentially are traversed by foreach loop@ H_ 301_ 2@
20. Use synchronization code block instead of synchronization method @ h_ 301_ 2 @ this has been made clear in the synchronized lock method block in the multithreading module. Unless it is determined that the whole method needs to be synchronized, try to use the synchronized code block to avoid synchronizing the code that does not need to be synchronized, which affects the code execution efficiency@ H_ 301_ 2@
21. Declare the constant as static final and name @ h with uppercase_ 301_ 2@ in this way, these contents can be put into the constant pool during compilation to avoid calculating the value of the generated constant during runtime. In addition, naming constants in uppercase also makes it easy to distinguish constants from variables @ H_ 301_ 2@
22. Do not create some unused objects or import some unused classes @ H_ 301_ 2@
This is meaningless if "the value of the local variable I is not used" and "the import Java. Net" appear in the code Util is never used ", please delete these useless contents @ H_ 301_ 2@
23. Avoid using reflection @ h during program operation_ 301_ 2@ for, see reflection. Reflection is a very powerful function provided by java to users. Powerful function often means low efficiency. It is not recommended to use the reflection mechanism, especially the invoke method of method, frequently during the running of the program. If necessary, a recommended approach is to instantiate an object of those classes that need to be loaded through reflection and put it into memory when the project is started - users only care about obtaining the fastest response speed when interacting with the opposite end, I don't care how long it takes to start the opposite project@ H_ 301_ 2@
24. Use database connection pool and thread pool @ h_ 301_ 2 @ both pools are used to reuse objects. The former can avoid frequent opening and closing connections, and the latter can avoid frequent creation and destruction of threads @ H_ 301_ 2@
25. Use buffered I / O stream for IO operation @ h_ 301_ 2@
Buffered input / output streams, i.e. BufferedReader, bufferedwriter, bufferedinputstream and bufferedoutputstream, can greatly improve IO efficiency @ H_ 301_ 2@
26. ArrayList is used for scenes with more sequential insertion and random access, and LinkedList @ h is used for scenes with more element deletion and intermediate insertion_ 301_ 2@
Well, you can understand the principles of ArrayList and LinkedList @ H_ 301_ 2@
27. Don't have too many formal parameters @ h in the public method_ 301_ 2@
Public methods are externally provided methods. If these methods are given too many formal parameters, they have two disadvantages: @ h_ 301_ 2@
1) It violates the object-oriented programming idea. Java emphasizes that everything is an object. Too many formal parameters do not fit with the object-oriented programming idea @ H_ 301_ 2 @ 2). Too many parameters will inevitably increase the error probability of method call @ H_ 301_ 2 @ as for the number of "too many", three or four. For example, we use JDBC to write an insertstudentinfo method. There are 10 student information fields to be inserted into the student table. These 10 parameters can be encapsulated in an entity class as the formal parameter @ h of the insert method_ 301_ 2@
28. When string variable and string constant equals, write the string constant in front of @ H_ 301_ 2 @ this is a common trick. If you have the following code:
It is suggested to modify it to: @ h_ 301_ 2@
This is mainly to avoid null pointer exception @ H_ 301_ 2@
32. Do not force downward transformation of basic data types beyond the range @ h_ 301_ 2@
33. Convert a basic data type to a string, basic data type Tostring() is the fastest way, string Valueof (data) takes the second place, data + "" slowest @ h_301_2 @ there are three ways to convert a basic data type. I have an integer data I, which can use i.tostring(), string. Valueof (I) and I + ". See a test for the efficiency of the three methods:
The operation result is:
Therefore, when converting a basic data type to string in the future, the toString () method is preferred. As for why, it's simple: @ h_ 301_ 2@ 1、String. The underlying valueof () method called integer Tostring() method, but short judgment @ h before calling_ 301_ 2@ 2、Integer. The toString () method doesn't mention it, but directly calls @ H_ 301_ 2 @ 3. The underlying layer of "I +" is implemented by StringBuilder. First, use the append method to splice, and then use the toString () method to obtain the string @ H_ 301_ 2 @ in comparison, 2 is the fastest, 1 is the second, and 3 is the slowest
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.