Summary of 35 Java code Performance optimizations

Source: Internet
Author: User
Tags modifier object object stringbuffer

Objective
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, reduce the volume of the Code
2, improve the efficiency of code operation

Code optimization Details

1. Specify the final modifier of the class and method as much as possible
A class with 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 will increase the 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 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. Use local variables whenever possible
Parameters passed when the method is called and temporary variables created in the call are saved in the stack faster, and other variables, such as static variables, instance variables, and so on, 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. Close the flow in time
In the Java programming process, the database connection, I/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, minimize the repetition of the variable calculation
To define a concept, the invocation of a method, even if there is only one sentence in the method, is also consumed, including creating a stack frame, protecting the site when invoking a method, recovering the site when the method is called, and so on. So for example, the following actions:
for (int i = 0; i < list.size (); i++) {...}
Suggested substitutions are:
for (int i = 0, int 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 loading strategy, that is, when needed to create
For example:
String str = "AAA"; if (i = = 1) {list.add (str);}
Suggested substitutions are:
if (i = = 1) {String str = "AAA"; List.add (str);}

7, cautious use of abnormal
Exceptions are 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...catch in the loop ..., you should put it on the outermost
Unless there is a last resort. If there is no reason to write this, as long as your leadership senior, obsessive, probably will scold you why write this garbage code

9. If you can estimate the length of the content to be added, specify the initial length for the collection that the underlying array implements, the tool class
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 with size characters assigned by default
(3) StringBuilder (String str)//default 16 characters +str.length () character space
It 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 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, 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, saving more than a space
(2) Copy the original 4,096 characters into the new character array.
In this way, both the memory space is wasted and the code runs efficiently. 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, use the system.arraycopy () command

11. Multiplication and division using shift operations
For example:
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 (int i = 1; I <= count; i++) {Object obj = new Object ();}
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 (int i = 0; I <= count; i++) {obj = new Object ();}
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, based on the efficiency and type checking considerations, should use as far as possible array, cannot determine the size of the array to use ArrayList

14, 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 resulting in performance costs

15. Do not declare the array as public static final
Because this is meaningless, it simply 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 the outer class

16, try to use a single case in the appropriate situation
Using a single example can reduce the load burden, shorten the load 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 concurrent access of resources
(2) control of the production of instances to achieve the purpose of saving resources
(3) Controlling the sharing of data, allowing multiple unrelated processes or threads to communicate without establishing a direct association

17, try to avoid arbitrary 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:
/ * Java Learning Chat QQ Group: 58980xxx we learn java! together. */public class a{private static b b = new B ();}
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 terminates

18. Timely removal of sessions that are no longer needed
In order to clear a session that is no longer active, many application servers have a default session timeout, which typically takes 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, the implementation of the Randomaccess interface, such as ArrayList, 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. You can use code like this to make a decision:
if (list instanceof randomaccess) {for (int i = 0; i < list.size (); i++) {}}else{iterator<span font-size:16px;line-he Ight:2; " = "style=" font-family: "Microsoft Yahei"; font-size:16px; Line-height:2; " >1, integer default data type is Int,long L = 12345678901234L, this number is beyond the range of int, so finally there is an L, indicating that this is a long type. By the way, the default type of float is double, so when you define float you 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, it is not a property within the method), 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 + "" slowest
To convert a basic data type to a general three ways, I have an integer data I, can use i.ToString (), string.valueof (i), i+ "" Three ways, three ways of efficiency, see a test:
public static void Main (string[] args) {int looptime = 50000;integer i = 0; Long startTime = System.currenttimemillis (); f or (int j = 0; J < Looptime; J + +) {String str = string.valueof (i);} System.out.println ("string.valueof ():" + (System.currenttimemillis ()-StartTime) + "MS"); startTime = System.currenttimemillis (); for (int j = 0; J < Looptime; J + +) {String str = i.tostring ();} System.out.println ("integer.tostring ():" + (System.currenttimemillis ()-StartTime) + "MS"); startTime = System.currenttimemillis (); for (int j = 0; J < Looptime; J + +) {String str = i + "";} System.out.println ("I +" ":" + (System.currenttimemillis ()-StartTime) + "MS");}
The result of the operation is:
String.valueof (): 11ms integer.tostring (): 5ms i + "": 25ms
Therefore, the ToString () method is preferred when you encounter a conversion of a basic data type into string. As for why, it's simple:
1. The string.valueof () method calls the Integer.tostring () method at the bottom, but it will be bearish before the call
2, Integer.tostring () method will not say, directly called the
3, i + "" bottom using StringBuilder implementation, first with the Append method splicing, and then use the ToString () method to get the string
In contrast, the three are clearly 2 fastest, 1 times, 3 slowest

34. Use the most efficient way to traverse the map
There are many ways to traverse a map, 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 void Main (string[] args) {HashMap (); Hm.put ("111", "222"); Set<map.entry> iter = Entryset.iterator (); while (Iter.hasnext ()) {Map.entry
<span font-size:16px;line-height:2; " = "" data-filtered= "Filtered" style= "font-family: Microsoft ya black; font-size:12px; White-space:normal; Background-color:rgb (255, 255, 255); " ></map.entry
<map.entry</map.entry

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.