Summary of performance optimizations for Java code

Source: Internet
Author: User
Tags object object sessions

35Summary of performance optimizations for Java codePreface 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 goals of code optimization are:1, reducing the volume of the Code2, improve the efficiency of code Execution code optimization details1, a class that specifies the final modifier of a class, method, and a final modifier 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 allows for an average performance increase%. 2, try to reuse objects, especially the use of String objects, you should use StringBuilder when string joins occur/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, the parameters passed when using local variables to invoke the method whenever possible, 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 runs, are gone, and no additional garbage collection is required. 4, in-time shutdown stream Java programming process, database connection, I/The o flow operation must be careful, when 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, minimizing the repetition 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 actions: for(inti = 0; I < list.size (); i++){...} Suggested substitutions are: for(inti = 0,intLength = List.size (); i < length; i++){...} In this way, when the list.size () is very large, it reduces a lot of consumption6and try to use lazy loading strategies that are created when needed, for example: String str= "AAA";if(i = = 1) {list.add (str);} Suggested substitutions are:if(i = = 1) {String str= "AAA"; List.add (str);} 7, the use of unusual anomalies is bad for performance. 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 in the loop ...Catch..., you should put it on the outermost layer unless you have to. If there is no reason to write this, as long as your leadership senior, obsessive, probably will scold you why write this garbage code9, if you can estimate the length of the content to be added, for the underlying array-based collection, the tool class to specify the initial length 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 (intSize//allocate space by default for size characters(3) StringBuilder (String str)//16 characters +str.length () character space is assigned by defaultIt is possible to set its initialization capacity through the class (which refers to 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 increases its capacity to the current twice times plus 2, and whenever StringBuilder reaches its maximum capacity, it has 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: (1On 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 initially specify a 5,000-size character array, you save more than a space (2Copy the original 4,096 characters into a new character array, wasting memory space and reducing the efficiency of your code. 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. But, note that like HashMap, this is an array+ list implementation, do not set the initial size as you estimate the size of the same, because only one table on the possibility of connecting an object is almost 0. The initial size proposal is set to the power of N of 2, if it can be estimated that there are 2000 elements, set to new HashMap (128),NewHASHMAP (256) are available. 10, when copying large amounts of data, use the system.arraycopy () command11, multiplication, and division use shift operations such as: for(val = 0; Val < 100000; val + = 5) {a= Val * 8; b= VAL/2;} The shift operation can greatly improve performance, because at the bottom of the computer, the bitwise operation is the most convenient and fastest, so it is recommended to modify: for(val = 0; Val < 100000; val + = 5) {a= Val << 3; b= Val >> 1;}  Although the shift operation is fast, it may make the code less understandable, so it's best to add the appropriate comments. 12, do not constantly create object references within the loop, for example: for(inti = 1; I <= count; i++) {Object obj=NewObject ();} This practice causes memory to count as the object reference exists, and if count is large, it consumes memory and is recommended instead: Object obj=NULL; for(inti = 0; I <= count; i++) {obj =NewObject ();}  In this case, only one copy of the object object is referenced in memory, and each time new object () is used, the object reference points to a different object, but only one copy in memory, which saves memory space considerably. 13, efficiency-based and type-checking considerations, you should use an array whenever possible, and use ArrayList when you cannot determine the size of the array14, try to use HashMap, ArrayList, StringBuilder, unless the thread security needs, it is not recommended to use Hashtable, Vector, StringBuffer, the latter three due to the use of synchronization mechanism caused by the performance cost 15. Do not declare an array as publicStatic Finalbecause it doesn't make sense, it just defines the reference as static.Final, the contents of the array can be arbitrarily changed, and declaring the array public is a security vulnerability, which means that the array can be changed by an external class16, as far as possible in the appropriate use of a single case can reduce 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 concurrent access to resources (2) control the generation of instances to achieve the goal of saving resources (3controls the sharing of data, enabling communication between multiple unrelated processes or threads without establishing a direct association17and try to avoid random use of static variables you know, when an object is referenced by a variable defined as static, the GC typically does not reclaim the heap memory that the object occupies, such as: Public classa{Private Staticb 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 referred to by B will reside in memory until the program terminates18To clear a session that is no longer needed in order to clear a session that is 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 () method should be called in time to clear the session. 19, a collection of randomaccess interfaces, such as ArrayList, should be traversed using the most common for loop instead of the Foreach loop, which is recommended by the JDK 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. You can use code like this to make a decision:if(Listinstanceofrandomaccess) {  for(inti = 0; I < list.size (); i++){}}Else{Iterator<?> iterator = list.iterable (); while(Iterator.hasnext ()) {Iterator.next ()}} The underlying implementation principle of the Foreach loop is the iterator iterator, see Java Syntax sugar 1: variable length parameters and the Foreach 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 the Foreach Loop to traverse. 20, using the synchronous code block instead of the synchronization method This is clearly stated in the synchronized lock method block in multithreaded modules, unless you can determine that a whole method needs to be synchronized, try to use synchronous blocks of code, and avoid synchronizing code that does not need to be synchronized.  affect the efficiency of code execution. 21. Declare a constant as staticFinaland named in uppercase so that it can be put into a constant pool during compilation, avoiding the calculation of the value of the generated constant during the run. In addition, it is easy to distinguish constants from variables by naming them in uppercase.22, do not create some unused objects, do not import some unused classes this is meaningless, if the code appears "the value of the local variable I am not used", "theImportjava.util is never used ", then please remove these useless content23, avoid using reflection about during program run, 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 to do so, it is recommended that the classes that need to be loaded by reflection 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, using the database connection pool and the thread pool are both used to reuse objects that avoid frequent opening and closing of connections, which avoids the frequent creation and destruction of threads25, using buffered input and output streams for IO operations with buffered input and output streams, i.e. BufferedReader, BufferedWriter, Bufferedinputstream, Bufferedoutputstream, This can greatly improve IO efficiency26, sequential insertion and random access more scenarios using ArrayList, element deletion and intermediate insertions more scenes using LinkedList this, understanding ArrayList and LinkedList principle will know27, do not let public methods have too many formal parameter public methods that are provided externally, if you give these methods too many parameters, there are two main disadvantages:1, violates the object-oriented programming idea, Java stresses that everything is object, too many formal parameters, and object-oriented programming ideas do not fit2, too many parameters will cause the error probability of the method call to increase as far as this "too much" refers to how many,3, 4 of them. 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 parameter of the Insert method28, string variables, and string constants the string constants are written in front of equals. This is a relatively common trick, if you have the following code: string str= "123";if(Str.equals ("123")) {...} Suggested modification to: String str= "123";if("123". Equals (str))  {...} This is done primarily to avoid null pointer exceptions29, please know, in Java if (i = = 1) and if (1 = =i) There is no difference, but from the reading habits, the former is recommended to use the first people ask, "if(i = = 1) "and"if(1== i) "There's no difference, it's going to be from C + +speak up. In CIn/c++, "if(i = = 1"The judging conditions are based on 0 and not 0, 0 for false, and not 0 for true, if there is such a code:inti = 2;if(i = = 1){...}Else{...} C/c++ judgment "i==1″ is not true, so it is 0, which means false. But if:inti = 2;if(i = 1) { ... }Else{ ... } In case the programmer a careless, put "if(i = = 1) "Written"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 is the case in C + +development is likely to occur and can cause 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:inti = 2;if(1 = = i) { ... }Else{ ... } This way, even if the developer accidentally wrote "1 = i ", C + +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, C/c++ this "if(i = 1) "The syntax is not possible, because once this syntax is written, Java will compile an error" Type Mismatch:cannot convert fromintToBoolean”。 However, although Java's "if(i = = 1) "and"if(1 = =i) "There is no semantic difference, but from a reading habit, it is better to suggest the former." 30, do not use the ToString () method on an array to see what the array is printed with ToString (): Public Static voidMain (string[] args) {int[] is =New int[]{1, 2, 3};  System.out.println (Is.tostring ());} The result: [[email protected] is intended to print an array of contents, but it is possible that the arrays reference is null, resulting in a null pointer exception. However, although the array ToString () does not make sense, the set ToString () can print out the contents of the collection, because the parent class of the collection Abstractcollections<E>overridden The ToString () method of object. 31, do not make a downward transition to the underlying data type that is out of scope this will never get the result you want: Public Static voidMain (string[] args) {LongL = 12345678901234L;inti = (int) L;  System.out.println (i);} We may expect to get some of them, but the result is:1942892530explain. In Java, Long is 8 bytes in 64 bits, so the 12345678901234 representation in a computer should be:0000 0000 0000 0000 0000 1011 0011 1010 0111 0011 1100 1110 0010 1111 1111 0010an int data is 4 bytes 32 bits, and the first 32 bits of this binary data are removed from the low:0111 0011 1100 1110 0010 1111 1111 0010This string binary is represented as a decimal 1942892530, so it is the output on the console above us. From this example, you can also get two conclusions:1, the integer default data type is int,LongL = 12345678901234L, this number is beyond the range of int, so there is an L, which indicates that this is a long number. By the way, the default type of float is double, so the definition of float is written "" Float F = 3.5f "2, then write another sentence"intII = l + i; " Will error, because long +int is a long and cannot be assigned to int32, common collection classes do 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 are not automatically freed, because references are always directed 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 base data type. ToString () is the quickest way, string.valueof (data), Data + "" slowestto convert a basic data type to a general there are three ways, I have an integer data I, can use i.ToString (), string.valueof (i), I+ "" Three ways, three ways of efficiency how to see a test: Public Static voidMain (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");} Operation Result: String.valueof (): 11ms integer.tostring (): 5ms I+ "": 25ms So when you encounter a conversion from a basic data type to a string, it is preferable to use the ToString () method. As for why, it's simple:1, the String.valueof () method is called the Integer.tostring () method, but is bearish before the call2, Integer.tostring () method is not said, directly called the3, i +" " The bottom uses the StringBuilder realization, first uses the Append method splicing, then uses the ToString () method obtains the string three compares, obviously is 2 fastest, 1 times, 3 slowest34, there are many ways to traverse a map in the most efficient way, and the most common scenario we need is to traverse the key and value in the map, so the most efficient way to use it is: Public Static voidMain (string[] args) {HashMap<string, string> HM =NewHashmap<string, string>(); Hm.put ("111", "222"); Set<map.entry<string, string>> entryset =Hm.entryset (); Iterator<map.entry<string, string>> iter = Entryset.iterator (); while(Iter.hasnext ()) {Map.entry<string, string> entry =Iter.next (); System.out.println (Entry.getkey ()+ "\ T" +Entry.getvalue ());}} If you just want to traverse the key value of this map, use the "Set<String> KeySet =Hm.keyset (); " would be more appropriate .35, the Close () recommendation of the resource operation means, for example, I have this piece of code:Try{xxx.close (); Yyy.close ();}Catch(Exception e) {...} Suggested changes to:Try{Xxx.close ();}Catch(Exception e) { ... }Try{Yyy.close ();}Catch(Exception e) {...} Although there is some trouble, it can avoid resource leakage. 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 performance optimizations for Java code

Related Article

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.