SOURCE | Personal Blog | Author | The Cangjie of the May
Original Address | See bottom description
This article is the author: May Cangjie The combination of his work and the experience of normal learning to reopen the reason for code optimization. Before the modification, the author's statement was as follows:
Just like a whale eats shrimp, maybe a two-shelled shrimp is not very useful for a whale, but a lot of shrimp is eaten and the whale is naturally full.
Code optimization, perhaps a two optimization, to improve the efficiency of the code is not significant, but as long as everywhere can pay attention to code optimization, in general, to improve the efficiency of the operation of the code is very useful.
This view, in the present, is a reason for code optimization, but not all right. In the development of mechanical technology today, the server 8 cores, 16 cores, 64-bit CPU, code execution efficiency is very high, StringBuilder replacement StringBuffer, ArrayList replacement vector, for the code to improve the efficiency of the operation is negligible, Even if every point in the project is noticed, the code does not see any noticeable change in its operation.
I think the most important role of code optimization should be: avoid unknown errors. In the process of running the code line, there are often many unexpected errors, because the online environment and development environment is very different, wrong positioning to the end is often a very small reason. However, in order to solve this problem, we need to validate, then package out the class file to be replaced, suspend the business and restart, for a mature project, the final effect is very large, which means that the user can not access the application in this period. Therefore, when writing code, from the source to pay attention to a variety of details, weighing and using the best choice, will largely avoid the unknown error, in the long run greatly reduce the workload.
first, the goal of code optimization is:
1, reduce the size of the code
2, improve the efficiency of code operation
The content of this article comes from the network, some from the normal work and learning, of course, it is not important, it is important that the details of the code optimization is really useful. This article will maintain a long-term update, as long as there is a need to share the code optimization details, it will update this article.
second, the 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 the efficiency of Java operations, as detailed in Java runtime optimizations. This will increase performance by an average of 50%.
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 on the stack, and the other variables, such as static variables, instance variables, and so on, are created in the heap at a slower rate. 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:
Suggested replacements are:
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
For example:
Suggested replacements are:
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, for the bottom of the array implementation of the collection, tool class to specify the initial length
For example, ArrayList, Linkedllist, StringBuilder, StringBuffer, HashMap, HashSet, etc., take StringBuilder as an example:
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 estimate 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:
On the basis of 4096, and then apply for 8,194 size of the character array, add up to apply for a 12,290 size character array, if the beginning can specify 5,000 size character array, save more than one time space;
Copy the original 4,096 characters into the new character array;
In this way, 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.
10. When copying large amounts of data, use the system.arraycopy () command
11. Multiplication and division use shift operations
For example:
Using shift operations can greatly improve performance, because at the bottom of the computer, bitwise manipulation is the most convenient and fastest, so it is recommended that you modify it to:
While the shift operation is fast, it may make the code less understandable, so it is best to add the appropriate annotation.
12. Don't keep creating object references within the loop
For example:
This can lead to the existence of Count object references in memory, which, when count is large, consumes memory, and is suggested to read:
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) The control example is produced to achieve the goal of saving resources;
(3) Control the sharing of data, without establishing the direct correlation, let a number of unrelated processes or threads to achieve communication between;
17, try to avoid the arbitrary use of static variables
You know, when an object is referenced by a variable that is defined as static, the GC usually does not reclaim the heap memory that the object occupies, such as:
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:
The underlying implementation of the Foreach loop is the iterator iterator, see Java Syntax sugar 1: variable length parameters and the Foreach Loop principle. So the second half of the sentence "in turn, if the sequential access, then use iterator will be more efficient" means that the sequential access to the class instances, 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, the Java emphasizes all is the object, too many formal parameters, and the object-oriented programming thought does not fit;
(2) Too many parameters will cause the error probability of method call increase;
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:
Recommended modifications to:
The main thing is to avoid null pointer anomalies.
29, please know that in Java if (i = = 1) and if (1 = = i) is no difference, but from the reading habits, suggest the use of the former
At ordinary times, someone asked, "if (i = = 1)" and "if (1== i)" There is no difference, this will be from C/A + + speaking.
In C + +, the "if (i = = 1)" condition is judged to be based on 0 and not 0, 0 for false, and not 0 for true, if there is such a piece of code:
C + + to judge "I==1″ is not tenable, so in 0, that is false." But if:
In case the programmer is careless, write "if (i = = 1)" As "if (i = 1)", which is problematic. Within if I is assigned to 1,if the contents of the content is not 0, the return is true, but obviously I is 2, the comparison value is 1, should return false. This situation is likely to occur in C + + development and can lead to some incomprehensible errors, so in order to avoid the developer's incorrect assignment in the IF statement, it is recommended that the IF statement be written as:
This way, even if the developer accidentally wrote "1 = i", the C + + compiler can also check out the first time, because we can assign a variable i to 1, but can not assign a constant value of 1 to I.
In Java, however, the syntax of "if (i = 1)" is not possible, because once this syntax is written, Java compiles the error "Type mismatch:cannot convert from int to Boolean". However, although the Java "if" (i = = 1) and "if (1 = i)" Are semantically indistinguishable, it is better to suggest that the former is used in reading habits.
30. Do not use the ToString () method on the array
Look at what the array uses ToString () to print:
It is intended to print the array of contents, but it is possible that the null pointer exception is caused by the empty index reference is. However, although the array ToString () does not make sense, the set ToString () can print out the contents of the collection because the collection's parent class Abstractcollections<e> overrides the object's ToString () method.
31, do not go beyond the scope of the basic data types do downward forced transformation
This will never get the desired result:
We might expect to get a few of them, but the result is:
Explain. In Java, Long is 8 bytes 64 bits, so the 12345678901234 representation on the computer should be:
0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111-1111 0010
An int data is 4 bytes 32 bits, and the top 32 bits of the above binary data are removed from the low level:
0111 0011 1100 1110 0010 1111 1111 0010
This string of binary notation is decimal 1942892530, so it's the output from the console above us. From this example, we can also get two conclusions by the way:
(1) The integer default data type is Int,long L = 12345678901234L, this number is beyond the range of int, so the last has an L, which means that this is a long number. By the way, the default type for floating-point types is double, so when you define float, write "float f = 3.5f"
(2) Then write another sentence "int II = L + i;" Error, because long + int is a long and cannot be assigned to int
32, the common collection class does not use the data must be removed in time
If a collection class is public (that is, not a property within a method), then the elements within the collection are not automatically freed because references are always directed to them. Therefore, if some of the data in the public collection does not use and remove them, it will cause this common set to increase, so that the system has a hidden memory leak.
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:
The results of the operation are:
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 invoked at the bottom of the string.valueof () method, but the judgment is shorted before the call;
(2) Integer.tostring () method is not said, directly called;
(3) i + "" "" "the bottom of the use of StringBuilder implementation, first with the Append method stitching, and then the ToString () method to obtain the string;
Compared to the three, it is obviously 2 fastest, 1 times, 3 slowest.
34, use the most efficient way to traverse the map
There are a lot of ways to traverse a map, and usually what we need is to traverse the key and value in the map, so the most efficient way to recommend it is:
If you just want to traverse the key value of this map, use "set<string> keyset = Hm.keyset ();" would be more appropriate.
35, close to the resource () proposed separate operation
It means, for example, I have this piece of code:
Recommended modifications to:
Although some trouble, but can avoid resource leakage. We think, if there is no modified code, in case Xxx.close () throw an exception, then entered the catch block, Yyy.close () will not execute, YYY this resource will not be recycled, has been occupied, such a code, is likely to cause the resource handle leakage. Instead, the following is the way to make sure that xxx and yyy will be close off anyway.
36, for threadlocal before use or after use must first remove
The current basic all projects are using the thread pooling technology, which is very good, you can dynamically configure the number of threads, you can reuse threads.
However, if you use threadlocal in your project, be sure to remember to use it or remove it before using it. This is because the thread pooling technique mentioned above is a thread reuse, which means that when the code is running, a thread is used and will not be destroyed but wait for the next use. Let's take a look at the thread class, which holds the Threadlocal.threadlocalmap reference:
The thread does not destroy means that the data in the threadlocal.threadlocalmap of the last thread set is still present, so when the next thread reuses the thread, it is possible to get to the data on the last thread set rather than what you want.
This question is very obscure, once the cause of this error, no relevant experience or no solid foundation is very difficult to find this problem, so in writing code to pay attention to this point, which will give you a lot of work to reduce the amount of effort.
37, remember to replace the devil number in the way of constant definition, the existence of the devil number will greatly reduce the readability of the code, whether the string constants use constant definitions can be
38, long or long when the initial assignment, the use of uppercase L rather than lowercase l, because the letter L is very easy to confuse with the number 1, this point is very detail, worth noting
39. All overridden methods must retain @override annotations
There are three reasons for doing this:
(1) It is clear to know that this method inherits from the parent class;
(2) GetObject () and Get0bject () method, the former fourth letter is "O", the latter is the fourth child is "0″, added @override annotation can immediately determine whether to rewrite success;"
(3) To modify the method signature in the abstract class, the implementation class will immediately report the compilation error;
40. It is recommended to use the new objects tool class introduced in JDK7 to compare the equals of objects, direct a.equals (b), the risk of NULL pointer anomalies
41, the circulation body does not use "+" carries on the string concatenation, but the direct use StringBuilder unceasingly append
Tell me why you don't use "+" for string concatenation if I have a method: