Summary of 35 Java code performance optimizations

Source: Internet
Author: User

Preface to the Code optimization, a very important topic. Some people may feel useless, some small places have what good change, change and do not change the efficiency of the operation of the code has any impact? That's the question I'm thinking about, like a whale in the sea, is it useful to eat a little shrimp? No, but after eating a little shrimp, the whale is fed. Code optimization is also the same, if the project focus on as soon as possible without a bug on-line, then you can grasp the large and small, the details of the code can not be fine grinding; but if there is enough time to develop and maintain the code, you have to consider every detail that can be optimized, a small optimization point accumulates, There is definitely an improvement in the efficiency of the code operation.
  
The goal of code optimization is: 1, reduce the volume of the Code 2, improve the efficiency of the code to run the code optimization details 1, try to specify the class, the final modifier of the method with the final modifier of the class is not derived. In the Java Core API, there are many examples of final applications, such as Java.lang.String, where the entire class is final. Specifying the final modifier for a class allows the class not to be inherited, and specifying the final modifier for a method allows the method not to be overridden. If a class is specified as final, all methods of the class are final. The Java compiler will look for opportunities to inline all final methods, and inline is important for improving the efficiency of Java operations, see Java Runtime Optimizations. This will increase the performance by an average of 50%.
  
2, as far as possible to reuse objects, especially the use of String objects, the string connection should use Stringbuilder/stringbuffer instead. Because Java virtual machines take time not only to generate objects, but may also take time to garbage-collect and process them later, generating too many objects will have a significant impact on the performance of the program.
  
3. Parameters passed when using local variables to invoke the method whenever possible and 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 runs, are gone, and no additional garbage collection is required.
  
4, in a timely way to shut down the flow of Java programming process, database connection, I/O flow operation must be careful, after the use is complete, close in time to release resources. Because the operation of these large objects can cause large overhead, and a slight carelessness, will result in serious consequences.
  
5, minimize the repeated calculation of the variable is a concept, the invocation of the method, even if there is only one sentence in the method, there is also consumption, including the creation of stack frames, the method is called to protect the scene, the call method is completed when the site recovery. So for example, the following action: The proposal is replaced by: this way, in the List.size () is very large, it reduces a lot of consumption 6, as far as possible to use lazy loading strategy, that is, when needed to create for example: {} suggested Replacement: {}7, Caution with exception exception to performance disadvantage. Throws an exception first to create a new object, the constructor of the Throwable interface calls the local synchronization method named Fillinstacktrace (), the Fillinstacktrace () method examines the stack, and collects the call trace 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 for control procedures.
  
8, do not use Try...catch in the loop ..., it should be placed in the outermost layer unless the last resort. If there is no reason to write this, as long as your leader, a bit of obsessive-compulsive disorder, probably will scold you why write this garbage code 9, if you can estimate the length of the content to be added, for the bottom array implementation of the collection, the tool class to specify the initial length such as ArrayList, Linkedllist, StringBuilder, StringBuffer, HashMap, HashSet, etc., take StringBuilder for example: (1) StringBuilder ()// The default allocation is 16 characters of space (2) StringBuilder (int size)//The default is assigned a size character of space (3) StringBuilder (String str)//default is assigned 16 characters +str.length () A character space can be used to set its initialization capacity through the class (which is not just the StringBuilder above), which can significantly improve performance. For example, StringBuilder, length indicates the number of characters the current StringBuilder can hold. Because when the StringBuilder reaches its maximum capacity, it will increase its capacity to the current twice times plus 2, whenever the StringBuilder reaches its maximum capacity, it will have to create a new character array and copy the old character array contents into the new character array-- This is an operation that is very expensive to perform. Imagine, if you can estimate the character array to hold 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, then apply 8,194 size of the character array, Add up to the equivalent of a 12,290-size character array, if you can initially specify 5,000-size character array, it saves more than one more space (2) to copy the original 4,096 characters into a new character array so that both wasted memory space and reduce the efficiency of code operation. Therefore, it is wrong to set a reasonable initialization capacity for the collection and tool class of the underlying array implementation, which will bring an immediate effect. Note, however, that a collection like HashMap is implemented as an array + linked list, so do not set the initial size to the size you estimate because it is almost 0 more likely to connect an object on a table. The initial size proposal is set to the power of N of 2, which can be set to new HashMap (128), and new HashMap (256) if it can be estimated to have 2000 elements.
  
10, when copying large amounts of data, using the system.arraycopy () command 11, multiplication and division using shift operations such as: {} with shift operation can greatly improve performance, because at the bottom of the computer, the operation of the bit is the most convenient and fastest, so it is recommended to modify: {} The shift operation, although fast, However, the code may not be well understood, so it is best to add the appropriate comments.
  
12. Do not constantly create object references within the loop for example: {} This practice causes count copies of object objects in memory to exist, the count is large, it consumes memory, the recommendation is to: In this case, only one copy of the object object reference in memory, each time new object () , the object reference refers to a different object, but only one copy in memory, which saves memory space considerably.
  
13, based on the efficiency and type checking considerations, should use the array as far as possible, can not determine the size of the array to use 14, try to use HashMap, ArrayList, StringBuilder, unless the thread security needs, it is not recommended to use Hashtable, Vectors, StringBuffer, and the latter three, due to the use of synchronization mechanisms resulting in a performance cost of 15, do not declare an array because it is meaningless, so just define the reference as static final, the contents of the array can be arbitrarily changed, Declaring an array as public is more of a security vulnerability, which means that the array can be changed by an external class 16, using a single case as much as possible in a suitable situation can alleviate the load burden, shorten the loading time, improve the efficiency of loading, but not all places are applicable to a single case, simply speaking, The single case is mainly applicable to the following three aspects: (1) control the use of resources, through thread synchronization to control the resources of concurrent access (2) control instances of the generation, in order to achieve the purpose of saving resources (3) control data sharing, in the condition of not establishing a direct association, let a number of unrelated processes or threads to achieve communication 17, Try to avoid random use of static variables you know, when an object is referenced by a variable 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 pointed to by B will be resident memory. Until the program terminates 18, clears the session that is no longer needed in order to clear sessions that are no longer active, many application servers have a default session time-out, typically 30 minutes. When the application server needs to save more sessions, if there is not enough memory, the operating system will transfer some of the data to disk, and the application server may dump partially inactive sessions to disk based on the MRU (most recently used) algorithm, and may even throw out-of-memory exceptions. If a session is to be dumped to disk, it must be serialized first, and the cost of serializing the object is expensive in a large-scale cluster. Therefore, when the session is no longer needed, the httpsession invalidate (www.6777188.cn) method should be called in time to clear the session.
  
19. To implement a collection of randomaccess interfaces such as ArrayList, you should use the most common for loop instead of the Foreach loop to traverse this is what the JDK recommends to the user. The JDK API's explanation for the Randomaccess interface is that the implementation of the Randomaccess interface is used to indicate that it supports fast random access, and the primary purpose of this interface is to allow a generic algorithm to change its behavior so that it can provide good performance when applied to random or contiguous access lists. The actual experience shows that the class instance that implements the Randomaccess interface, if it is random access, uses the normal for loop efficiency higher than the Foreach loop, and conversely, if it is accessed sequentially, the use of iterator is more efficient. It can be judged using code like the following:} The underlying implementation of the loop is the iterator iterator, see Java Syntax sugar 1: variable length parameters and loop principle. So the latter half of the sentence "in turn, if it is sequential access, the use of iterator will be more efficient" means that sequential access to those class instances, using loops to traverse.
  
20, using synchronous code block to replace the synchronization method this is in the multi-threaded module synchronized Lock method block in the article has been very clear, unless it can be determined that the entire method is required to synchronize, otherwise try to use synchronous code block, avoid the need to synchronize the code is also synchronized, affect the efficiency of code execution.
  
21. Declare a constant as static final and name it in uppercase so that it can be put into a constant pool during compilation, avoiding the value of the generated constant during run time. In addition, the names of the constants can be easily distinguished by the name of the constant and variable 22, do not create some unused objects, do not import some unused classes that meaningless, if the code appears "the value of the local variable i is not used", "the Import Java.util is never used ", then remove these useless content 23, avoid using reflection during program run about, see reflection. Reflection is a powerful feature that Java provides to the user, and powerful often means less efficient. It is not recommended to use the Invoke method especially when using the reflection mechanism, especially the method, when the program is running, and if it is necessary, it is suggested that the classes that need to be loaded by reflection will instantiate an object and put it into memory by reflection when the project is started-- The user only cares about the fastest response time when interacting with the peer, and does not care how long it takes to start the project on the end.
  
24. Use the database connection pool and thread pool both are used to reuse objects, the former can avoid frequent opening and closing of the connection, the latter can avoid the frequent creation and destruction of thread 25, using buffered input and output stream for IO operation with buffered input and output stream, namely BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream, which can greatly improve IO efficiency by 26, sequential insertion and random access to more scenes using ArrayList, Element Delete and intermediate insert more scenes Use this, understand the principle of ArrayList and LinkedList know 27, do not let public methods have too many formal parameter methods that are provided externally, if you give these methods too many parameters, there are two disadvantages: 1. Violates the object-oriented programming idea, Java stresses everything is object, too many formal parameters, and object-oriented programming ideas do not fit 2, too many parameters will inevitably lead to the error probability of the method call increase as to 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 parameter 28, string variables and string constants when you write string constants in the Equals, this is a relatively common trick, if you have the following code: ...
  
} suggested changes to: {...
  
The main thing to do is to avoid the null pointer exception 29, know that in Java if (i = = www.thd540.com 1) and if (1 = = i) is no difference, but from the reading habit, the former is recommended to ask, "if (i = = 1)" and "if (1== i)" has There's no difference, it's going to start with C + +.
  
The "if (i = = 1)" Criterion is determined by 0 and non-0, 0 for false, and not 0 for true, if there is such a piece of code: {...
  
...
  
} judged that "I==1″ is not true, so it is 0, that is, false." But if: In case the programmer is careless, write "if (i = = 1)" As "if (i = 1)", so there is a problem. If I is assigned to 1,if within if the content is not 0, the return is true, but clearly I is 2, the value of the comparison is 1, should return false. This situation is most likely to occur in the development of C/s + + 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 follows: This way, even if the developer accidentally writes "1 = i" The compiler can also check out the first time, because we can assign a variable i to 1, but cannot assign a value of 1 to a constant I.
  
However, in Java, the syntax for this "if (i = 1)" is not possible, because once this syntax is written, Java compiles an error "Type mismatch:cannot convert from int to Boolean". However, although Java's "if (i = = 1)" and "if (1 = = i)" Have no semantic differences, it is better to use the former in terms of reading habits.
  
30. Do not use the ToString () method on an array to see what the array is printed with ToString ():} The result is that the intent is to print an array of contents, but it is possible that the null pointer exception is due to the fact that the arrays reference is null. However, although the array ToString () does not make sense, the set ToString () is able to print out the contents of the collection, because the parent of the collection Abstractcollections<e> overrides the ToString () method of object.
  
31. Do not make a downward transition to the underlying data type that is out of range this will never get the desired result: {} We may expect to get some of them, but the result is: explain. In Java, Long is 8 bytes, 64 bits, so 12345678901234 in the computer representation should be: An int data is 4 bytes 32 bits, from the low out of the first 32 bits of this string of binary data is: This string binary is represented as a decimal 1942892530, So that's what we're outputting on the console above. In this case, you can also get two conclusions: 1, the default data type of the integer is Int,long l = 12345678901234L, this number is beyond the range of int, so there is an L, which indicates that this is a long type. By the way, the default type of float is double, so the definition of float is written in 2, followed by the words "int II = L + i;" Will error, because long + int is a long, cannot be assigned to Int32, the common collection class does not use the data must be removed in time if a collection class is common (that is, it is not a property within the method), then the elements inside the collection will not be automatically released, Because references are always pointed to them. Therefore, if some of the data in a common collection is not used without going to remove them, it will cause this common set to grow, causing the system to have a hidden memory leak.
  
33. To convert a basic data type to a string, the basic data type. ToString () is the quickest way, string.valueof (data), Data + "" slowest to convert a basic data type to a general three ways, I have an integer data i, You can use i.ToString (), string.valueof (i), i+ "" Three ways, three ways of efficiency, see a test: {{}:{}:{}:} The result is:: 11ms integer.tostring ( www.hjdseo.cn): 5ms i + "": www.thd1956.com/25ms So when it comes to converting a basic data type to string, the ToString () method is preferred. As for why, it is very simple: 1, the String.valueof () method is called the bottom integer.tostring () method, but will be short before the call Judgment 2, integer.tostring () method does not say, directly call the 3, i + "" The bottom uses the StringBuilder realization, first uses the Append method splicing, then uses the ToString () method obtains the string three compares down, obviously is 2 fastest, 1 times, 3 slowest 34, uses the most efficient way to traverse the map to traverse the map the way has many, Usually we need to traverse the key and value in the map, so the most efficient way to use it is: {{}} if you just want to traverse the key value of this map, use "set<string> KeySet = Hm.keyset ();" It'll be more appropriate. 35, close () recommendations for resources separate operation meaning, for example, I have this piece of code: try{{...
  
It is recommended that you avoid resource leaks, although it may be troublesome. We think, if there is no modified code, in case Xxx.close () throws an exception, then into the Cath block, Yyy.close () will not execute, YYY this resource will not be recycled, has been occupied, such a lot of code, is likely to cause the disclosure of resource handle. And instead of the following wording, it is guaranteed that XXX and yyy will be close off anyway.

Summary of 35 Java code performance optimizations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.