Code optimization Details
1, as far as possible to specify the final modifier class, method
A class with the final modifier is not derived. In the Java Core API, there are many examples of final application, such as java.lang.String, where the entire class is final. Specifying the final modifier for a class allows a class not to be inherited, and specifying the final modifier for a method can allow the method to be overridden. If you specify that a class is final, all methods of that class are final. The Java compiler looks for opportunities to inline all final methods, and inline is important for improving Java's operational efficiency
2. Reuse objects as much as possible
In particular, the use of String objects should be replaced with stringbuilder/stringbuffer when strings are concatenated. Because Java virtual machines not only take time to generate objects, they may also take time to garbage collect and process these objects, so generating too many objects will have a significant impact on the performance of the program.
3. Use local variables whenever possible
The parameters passed when the method is invoked and the temporary variables created in the call are saved in the stack faster, and other variables, such as static variables, instance variables, etc., are created in the heap and are slower. In addition, the variables created in the stack, as the method is run over, are gone and no additional garbage collection is required.
4, in time to close the flow
Java programming process, the database connection, I/O flow operation must be careful, after the use, timely shutdown to release resources. Because the operation of these large objects will cause a large system overhead, a slight carelessness, will lead to serious consequences.
5, minimize the duplication of the calculation of variables
Clear a concept, the call to the method, even if only one sentence in the method, is also consumed, including the creation of stack frames, call methods to protect the scene, when the method is completed to restore the scene. So for example, the following actions:
for (inti = 0; i < list.size (); i++)
{...} Suggested replacements are:
for (inti = 0, length = list.size (); i < length; i++)
{...}
In this way, when the list.size () is very large, it reduces a lot of consumption
6, try to use lazy load strategy, that is, when needed to create
7, careful use of abnormal
Exceptions are bad for performance. Throwing an exception first creates a new object, the constructor of the Throwable interface calls a local synchronization method named Fillinstacktrace (), and the Fillinstacktrace () method checks the stack to collect call tracking information. Whenever an exception is thrown, the Java Virtual machine must adjust the call stack because a new object is created during the process. Exceptions can only be used for error handling and should not be used to control the process.
8, do not use Try...catch in the loop ..., you should put it in the outermost
According to the comments made by netizens, I think it is worth discussing
9, if you can estimate the length of content to be added, specify the initial length for the underlying collection, the tool class, which is implemented as an array,
such as ArrayList, Linkedllist, StringBuilder, StringBuffer, HashMap, HashSet, and so on, take StringBuilder as an example:
(1) StringBuilder ()///16-character space is assigned by default
(2) StringBuilder (int Size)///Space
(3) StringBuilder (String str)//default allocation of 16 characters +str.length () character space
You can set its initialization capacity by the constructor of a class (not just the StringBuilder above), which can significantly improve performance. For example, StringBuilder, length represents the number of characters the current StringBuilder can hold. Because when StringBuilder reaches its maximum capacity, it increases its capacity to the current twice-fold plus 2, and whenever the StringBuilder reaches its maximum capacity, it has to create a new character array and then copy the old character array contents to the new character array-- This is a very performance-intensive operation. Just imagine, if you can predict the character array to store about 5,000 characters without specifying the length, the nearest 5000 of the 2 power is 4096, each expansion plus 2 regardless, then:
(1) on the basis of 4096, and then apply 8,194 size of the character array, Add up to the equivalent of a 12,290-size character array, if you can first specify a 5,000-size character array, you save more than one space
(2) Copy the original 4,096 characters into the new character array
Both waste memory space and reduce the efficiency of code operation. Therefore, it is not correct to set a reasonable initialization capacity for the underlying array and the tool class, which will result in an immediate effect. But note, like HashMap, this is a collection of array + linked lists, and don't set the initial size to the size you estimate, because the probability of connecting only one object on a table is almost 0. The initial size is proposed to be set to the N-Power of 2, if you can estimate 2000 elements, set to new HashMap (128), new HASHMAP (256) can be. &NBSP
10. When copying large amounts of data, use the system.arraycopy () command
11. Multiplication and division use shift operations
12. Don't keep creating object references within the loop
For example:
for (inti = 1; I <= count; i++)
{
Object obj = NewObject ();
}
This can lead to the existence of Count object references in memory, which, when count is large, consumes memory, and is suggested to read:
Object obj = null;
for (inti = 0; I <= count; i++)
{
obj = NewObject ();
}
In this case, there is only one object reference in memory, each time new object (), the object reference point to a different object, but only one in memory, which greatly saves memory space.
13, based on efficiency and type checking considerations, should use the array whenever possible, cannot determine the size of the array to use the ArrayList
14, try to use HashMap, ArrayList, StringBuilder, unless the thread security needs, otherwise do not recommend the use of Hashtable, Vector, StringBuffer, the latter three due to the use of synchronization mechanism resulting in performance costs
15, do not declare the array as public static final
Because it makes no sense to just define the reference as static final, the contents of the array can be changed at will, and declaring the array as public is a security vulnerability, which means that the array can be changed by an external class
16, as far as possible in the appropriate occasions to use a single case
Using a single example can reduce the load burden, shorten the load time, increase the efficiency of loading, but not all places are applicable to the single case, in simple terms, the single case mainly applies to the following three aspects:
(1) Controlling the use of resources and controlling the concurrent access of resources through thread synchronization
(2) Control instance is produced to achieve the goal of saving resources
(3) Control the sharing of data, without establishing a direct correlation, so that multiple unrelated processes or threads to achieve communication between
17, try to avoid the arbitrary use of static variables
public class A
{
private static B = Newb ();
}
At this point, the life cycle of static variable B is the same as Class A, and if Class A is not unloaded, the B object referenced by reference B will reside in memory until the program terminates
18, timely removal of the session no longer needed
To purge sessions that are no longer active, many application servers have a default session timeout, typically 30 minutes. When an application server needs to save more sessions, if there is not enough memory, the operating system transfers some of the data to disk, and the application server may dump some inactive sessions to disk based on the MRU (most recently used) algorithm, and may even throw out an out-of-memory exception. If the session is to be dumped to disk, it must be serialized first, and in a large cluster the cost of serializing the object is expensive. Therefore, when the session is no longer needed, the httpsession invalidate () method should be called in time to clear the session.
19, the implementation of the Randomaccess interface of the collection, such as ArrayList, should use the most common for loop rather than the Foreach loop to traverse
This is recommended by JDK to the user. The JDK API's interpretation of the Randomaccess interface is that the implementation of the Randomaccess interface is used to indicate that it supports fast random access, and that the main purpose of this interface is to allow a generic algorithm to change its behavior so that it can be applied to a random or sequential access list to provide good performance. Practical experience shows that if the class instance that implements the Randomaccess interface is randomly accessed, the use of the normal for loop efficiency will be higher than that of the Foreach loop, and conversely, if it is sequentially accessed, the use of iterator will be more efficient. You can use code similar to the following to make a judgment:
if (list instanceofrandomaccess)
{for
(inti = 0; i < list.size (); i++) {}
}
else
{
iterator <?> iterator = list.iterable ();
while (Iterator.hasnext ()) {Iterator.next ()}
}
The underlying implementation of the Foreach loop is the iterator iterator, so the second half of the sentence "Conversely, if sequentially accessed, the use of iterator will be more efficient" means that the class instances of sequential access, using the Foreach Loop to traverse.
20. Use synchronous code block instead of synchronization method
This point in the multithreaded module of the synchronized lock method block is very clear, unless you can determine that a whole method needs to be synchronized, otherwise try to use the synchronized code block, avoid the need for synchronization of those code is also synchronized, affecting the efficiency of code execution.
21. Declare the constants as static final and name them in uppercase
This allows the content to be placed in a constant pool during compilation, avoiding the calculation of the value of the generated constant during run time. In addition, you can easily distinguish between constants and variables by naming the constants in uppercase
22, do not create some unused objects, do not import some unused classes
This is meaningless, if "the value of the local variable I am used", "the import java.util is never used" appears in the code, please remove these useless content
23. Avoid using reflection during program operation
about, see reflection. Reflection is Java to provide users with a very powerful function, powerful often means that the efficiency is not high. It is not recommended that you use the Invoke method especially frequently using reflection mechanisms, especially methods, when the program is running, and if it is really necessary, a recommendation is to have classes that need to be loaded by reflection to instantiate an object and put it into memory at the start of the project-- Users only care about the time to get the fastest response when interacting with the end, and don't care how long it takes to start the project.
24. Use database connection pool and thread pool
Both pools are used to reuse objects, which avoid frequent opening and closing of connections, which avoids the frequent creation and destruction of threads
25. IO operation with buffered input/output stream
Buffered input/output streams, i.e. BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream, which can greatly enhance IO efficiency
26, sequential insertion and random access more scenes using ArrayList, element deletion and middle insert more scenes using LinkedList
This, understanding the principles of ArrayList and LinkedList, you know.
27, do not let the public method has too many formal parameters
The public method is the externally provided method, which has two disadvantages if you give too many formal parameters to these methods:
1, violates the object-oriented programming idea, Java emphasizes all is the object, too many formal parameters, and the object-oriented programming thought does not agree with
2), too many parameters will cause the method call error probability increased
As for this "too much" refers to how many, 3, 4 bar. For example, we use JDBC to write a insertstudentinfo method, there are 10 student information fields to be inserted into the student table, you can encapsulate these 10 parameters in an entity class, as the insert method of the formal parameters
28, string variables and string constants equals when the string constants are written in the front
This is a more common trick if you have the following code:
String str = "123";
if (Str.equals ("123"))
{
...
}
Recommended modifications to:
String str = "123";
if ("123". Equals (str))
{
...
}
The main thing is to avoid null pointer anomalies.
32, do not go beyond the scope of the basic data types do downward forced transformation
33. Convert a basic data type to a string, basic data type. ToString () is the fastest way, string.valueof (data) second, data + "" slowest
There are three ways to convert a basic data type, I have an integer data I, can use i.ToString (), string.valueof (i), i+ "" Three ways, three ways of efficiency, see a test:
publicstatic void Main (string[] args)
{
intlooptime = 50000;
Integer i = 0;
Longstarttime = System.currenttimemillis ();
for (INTJ = 0; J < Looptime; J +)
{
String str = string.valueof (i);
}
System.out.println ("string.valueof ():" + (System.currenttimemillis ()-StartTime) + "MS");
StartTime = System.currenttimemillis ();
for (INTJ = 0; J < Looptime; J +)
{
String str = i.tostring ();
}
System.out.println ("integer.tostring ():" + (System.currenttimemillis ()-StartTime) + "MS");
StartTime = System.currenttimemillis ();
for (INTJ = 0; J < Looptime; J +)
{
String str = i + "";
}
System.out.println ("i + \" \ ":" + (System.currenttimemillis ()-StartTime) + "MS");
}
The results of the operation are:
String.valueof (): 11ms
integer.tostring (): 5ms
i + "": 25ms
Therefore, it is preferable to use the ToString () method when encountering a basic data type as a string. As for why, it's simple:
1. The integer.tostring () method is called at the bottom of the string.valueof () method, but it is shorted before the call
2, Integer.tostring () method is not said, directly called the
3, i + "" "bottom of the use of StringBuilder implementation, first with the Append method stitching, and then the ToString () method to get the string
Compared to the three, it is obviously 2 fastest, 1 times, 3 slowest
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.